我有一个带有构造函数和几个属性的类。
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?