我想在我的javascript对象上创建一个依赖属性。我在代码片段中有一个对象。我想更新isPawn属性;当isNew属性更改时。
是否有一种方法可以自动执行类似的操作;
if(isNew){
isPawn = true;
}
但是它们不必相同。当isPawn为'true'时,isNew可以为'false'
我的对象:
var Soldier = function (id,name) {
this.id = id;
this.name = name;
this.isPawn = false;
this.isNew = false;
}
是,您可以使用设置器来完成此操作,下面是一个示例:
const isNewSym = Symbol('isNew');
class Soldier {
constructor(id,name) {
this.id = id;
this.name = name;
this.isPawn = false;
this[isNewSym] = false;
}
set isNew(val) {
this[isNewSym] = val;
this.isPawn = val;
}
get isNew() {
return this[isNewSym];
}
}
const soldier = new Soldier();
soldier.isNew = true;
console.log('isNew:', soldier.isNew, 'isPawn', soldier.isPawn);