Search code examples
javascriptclassobjectgettersetter

Changing object attributes in JS


I am new to javascript, so sorry in advance if this is a dumb question.

I am trying to make a class toDo, which is suppose to represent items in a to-do list. The items (or objects) should have a name and a state. The state is called done, and represents whether the item on the list is done or not. When constructing an object, I set done=false as default. However, I want my class to have the functionality so that I can change it to done=true. My attempt is shown below. I don't understand why the output is false if I call the status setter to change done to done=true.

All tips and explanations are appreciated. As you probably can see from the code, I'm pretty new to this. Thanks.

class toDo {
    constructor(name,done=false) {
        this.name = name;
        this.done = done;
    }

    get name() {
        return this._name;
    }

    get status() {
        return this._done;
    }

    set name(value) {
        this._name = value;
    }

    set status(state=true) {
        this._done = state;
    }

    
    /*set itemDone(state=true) {
        this._done = state;
    }*/

} 

var item1 = new toDo("Eat lunch");
console.log(item1.name);
item1.status;
console.log(item1.done);

The output I get is:

Eat lunch
false

Solution

  • As mentioned in the comments your syntax of calling setter is not correct. There is also a typo in the code with _done and done. Either remove the underscore completely or use it everywhere. Here is how I would change the code.

    
    class toDo {
        constructor(name,done=false) {
            this._name = name;
            this._done = done;
        }
    
        get name() {
            return this._name;
        }
    
        get status() {
            return this._done;
        }
    
        set name(value) {
            this._name = value;
        }
    
        set status(state=true) {
            this._done = state;
        }
    
        
        /*set itemDone(state=true) {
            this._done = state;
        }*/
    
    } 
    
    var item1 = new toDo("Eat lunch");
    console.log(item1.name);
    item1.status = undefined; //item.status = true will work here. item.status = null will not work here.
    
    console.log(item1._done);
    
    

    As you can see, you have to use item.state = "x" or something similar to call the setter. You are expecting it to work since it has a default parameter but this is not the case. I have called the setter with undefined and even then it works, showing that your default parameter of true is doing its job.

    Extra Note : You cannot do the same with null because null means an empty value and that is not the same as undefined. If you pass it to any function with default params that param will take the value null.