3

我有一个带有构造函数和几个属性的类。

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

注意到当我在创建对象时设置 Id 时,不使用设置器。

如何使在构造函数中设置的 Id 使用 setter?

4

1 回答 1

1

你没有Id在构造函数中设置,设置它(使用setter),使用这个:

this.Id = Id;

这是一个例子:

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

于 2019-10-20T12:33:12.923 回答