2

I try to use setter method with my class Test but my log return "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);

I expect the ouput will be 12 but i obtain TypeError.

Tristan_CH
  • 31
  • 1
  • 4

1 Answers1

1

To use a setter, you do assignment, you don't write a function call:

testObject.id = 12;

Live Example (I've also changed the name to Test; the overwhelming convention in JavaScript is to capitalize constructor functions):

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
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875