javascript - ES6 类 - 错误的构造函数和 setter 行为

标签 javascript ecmascript-6

我需要使用 setters insight 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 的 getter,所以你为什么会得到 undefined。

这个this.xPos = 0;xPos调用了setter,但是当你要写值的时候,它会为它找一个变量或者getter ,但你没有任何一个。在你的情况下,你需要使用值,或者为它编写一个 getter。

在示例中,我正在使用 getterssetters。在 setter 中,我设置属性值并读取 throw gettergetter 返回属性的值。

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();

关于javascript - ES6 类 - 错误的构造函数和 setter 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42834021/

相关文章:

javascript - 回调函数中的jQuery回调函数

javascript - 为什么我的模块的执行顺序与预期不同?

javascript - 使用 Webpack 和 Babel 将 ES6 转换为 AMD

node.js es6 使用 index.js 导出/导入

javascript - 为什么找不到我自己的自定义模块?

javascript - JsTree如何在刷新时load_all节点

javascript - 使用Meteor Spotify API根据单词搜索返回专辑列表,需要为列表中的每个专辑拉入轨道

javascript - 了解启用超时

javascript - 设置 openlayers 弹出窗口大小的正确方法是什么?

javascript - 为什么我不能通过对象中定义的字符串调用 setter?