Muhammad Rizwan
Muhammad Rizwan

Reputation: 203

JavaScript/ES6 property does not use setter when setting the value in the constructor

I have a class with a constructor and a couple of properties.

const _id = new WeakMap();

class Product {
    constructor(Id) {
        _id.set(this, Id);  // set 
    }
    get Id(){
        return _id.get(this);
    }
    set Id(value){
        if(value <= 0) throw new Error("Invalid Id");
        _id.set(this, value);
    }
    show() {
        alert(`Id : ${_id.get(this)}`);  // get 
    }
}


const p = new Product(-3);
// p.Id = -5;        // set 
window.alert(p.Id);   // get  (-3) problem ???  

// p.show();

Noticed when I set Id in on creation of the object the setter is not used.

How can I make the Id set in the constructor make use of the setter?

Upvotes: 3

Views: 272

Answers (1)

Titus
Titus

Reputation: 22474

You're not setting the Id in the constructor, to set it (use the setter), use this:

this.Id = Id;

Here is an example:

const _id = new WeakMap();

class Product {
    constructor(Id) {
        this.Id = Id;
    }
    get Id(){
        return _id.get(this);
    }
    set Id(value){
        if(value <= 0) throw new Error("Invalid Id");
        _id.set(this, value);
    }
    show() {
        alert(`Id : ${_id.get(this)}`);  // get 
    }
}


const p = new Product(-3);
// p.Id = -5;        // set 
window.alert(p.Id);   // get  (-3) problem ???  

// p.show();

Upvotes: 1

Related Questions