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
    To use the property's setter, you will have to assign to the property!? `this.Id = Id;`. – Bergi Oct 20 '19 at 15:01

1 Answers1

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();
Titus
  • 20,544
  • 1
  • 19
  • 29