【问题标题】:I can't use setter's in my javascript class because is not a function [duplicate]我不能在我的javascript类中使用setter,因为它不是一个函数[重复]
【发布时间】:2019-12-25 09:54:40
【问题描述】:

我尝试在我的类 Test 中使用 setter 方法,但我的日志返回“TypeError: testObject.id is not a function”

class test {

    constructor() {
        this._id = 0;
    }

    get id(){
        return this._id;
    }

    set id(newId){
        this._id = newId;
    }
}

const testObject = new test();
console.log(testObject.id); // return 0
testObject.id(12); //return TypeError: myTest.id is not a function
console.log(testObject.id);

我希望输出为 12,但我得到了 TypeError。

【问题讨论】:

    标签: javascript node.js class


    【解决方案1】:

    要使用 setter,您需要进行赋值,而不是编写函数调用:

    testObject.id = 12;
    

    实时示例(我也将名称更改为Test;JavaScript 中的压倒性约定是将构造函数大写):

    class Test {
    
        constructor() {
            this._id = 0;
        }
    
        get id(){
            return this._id;
        }
    
        set id(newId){
            this._id = newId;
        }
    }
    
    const testObject = new Test();
    console.log(testObject.id); // 0
    testObject.id = 12;
    console.log(testObject.id); // 12

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-14
      • 2021-06-18
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多