假设我有一个定义如下的类:
class MyClass {
constructor (a) {
this.a = a;
}
_onPropertyChanged() {
// do something
}
}
每当MyClass实例的属性“a”更改时,我都想在该实例上触发_onPropertyChanged方法。
使用ECMAscript 6实现此目标的最佳(性能最高)方法是什么?
最佳答案
没有“最佳”方法,实际方法始终取决于最终目标。
以其简单化(和足够的性能)形式,它是:
class MyClass {
constructor (a) {
this.a = a;
}
get a() {
return this._a;
}
set a(val) {
this._a = val;
this._onPropertyChanged('a', val);
}
_onPropertyChanged(propName, val) {
// do something
}
}
关于javascript - ECMAscript 6 : watch changes to class properties,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43461248/