3

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?

1
  • 1
    To use the property's setter, you will have to assign to the property!? this.Id = Id;. Commented Oct 20, 2019 at 15:01

1 Answer 1

1

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();

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.