setter js 无法在 javascript 中设置相同的变量 this 。 setter 和 getter 需要具有相同的名称

问题描述 投票:0回答:1

我有一个逻辑需要反应性地运行一些函数
如果

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 上执行逻辑。

希望你明白我的想法。谢谢

javascript class oop getter-setter
1个回答
0
投票

您可以使用私有属性

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)

© www.soinside.com 2019 - 2024. All rights reserved.