我有一个逻辑需要反应性地运行一些函数
如果
this.variableName
在课堂内外发生变化
问题出在这个逻辑上,getter 不起作用,我得到了
undefined
。
不仅如此,还有最大堆栈错误。
因为就像:在 setter 中设置
this
,重新设置 this
,再次调用 setter,设置 this,依此类推...(但这不是什么)我的意思是)
简化版本,没有参数,所以,只是错误的最小示例。
class MyClass {
constructor() {
this.isOn = false;
}
set isOn(value) {
this.isOn = value;
// another functions that do stuff. you can put here a bunch of console.logs if you want just for the demo
}
// the idea is another, but i will show you the simpliest method, I could imagine, just to make you get the idea
turnOn() {
this.isOn = true;
}
turnOff() {
this.isOn = false;
}
// using this approach,
// I don't need to copy paste the same functions in this 2 methods,
// so I just need to care about the var,
// without using a imperative approach,
// but a declarative approach
}
我知道我们可以使用_isOn,
但这实际上与我们想要的相反,
因为我希望setter与getter同名,
仍然在 setter 上执行逻辑。
希望你明白我的想法。谢谢
您可以使用私有属性
class MyClass {
#isOn = false;
set isOn(value) {
this.#isOn = value;
}
get isOn() {
return this.#isOn
}
turnOn() {
this.#isOn = true;
}
turnOff() {
this.#isOn = false;
}
}
const x = new MyClass
x.isOn = true
console.log(x.isOn)
// This will throw an error:
// console.log(x.#isOn)