繁体   English   中英

ES6类-错误的构造方法和设置方法行为

[英]ES6 classes - Wrong constructor and setters behavior

当实例的某些属性更改时,我需要使用setters洞察ES6 classes自动调用某些方法。

我这样写:

class Some {
  constructor () {
    this.xPos = 0;
    this.yPos = 0;
  }

  set xPos (value) {
    console.log(`xPos ${this.xPos}`);
  }

  set yPos (value) {
    console.log(`yPos ${this.yPos}`);
  }
}

let some = new Some();

但是控制台输出:

xPos undefined
yPos undefined

您没有xPosyPos吸气剂,所以为什么要不确定。

this.xPos = 0; 调用xPos setter,但是当您要编写值时,它将为它找到一个变量或一个getter,但是您没有任何变量。 在这种情况下,您需要使用价值,或者为此而写一个吸气剂。

在示例中,我正在研究getterssetters setter我设置属性的值并读取throw getter getter返回属性的值。

 class Some { constructor () { this.xPos = 0; this.yPos = 0; } set xPos (value) { this.xPosProp = value; console.log(`xPos ${this.xPos}`); } set yPos (value) { this.yPosProp = value; console.log(`yPos ${this.yPos}`); } get xPos () { return this.xPosProp; } get yPos () { return this.yPosProp; } } let some = new Some(); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM