Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 264
Muhammad Rizwan Avatar asked Mar 04 '26 19:03

Muhammad Rizwan


1 Answers

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();
like image 146
Titus Avatar answered Mar 07 '26 07:03

Titus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!