【问题标题】:ES6 Setting PropertiesES6 设置属性
【发布时间】:2016-11-05 06:53:52
【问题描述】:

我已经研究过了,似乎 ES6 没有设置类的属性并返回该类的能力?

class MyClass {
    constructor() {
        this.x = 0;
        this.y = 0;
    }
    update(value) {
        // logic
        this.y = value;
        return value;
    }
}

var x = new MyClass();
console.log(x.update(1));

使用上述方法,x 将保持 y 为 0,即使将 y 设置为 1console.log 将推出 1,但 y 从未真正更新。调用x.y 将导致0

我也尝试过返回课程,但这也不起作用。

class MyClass {
    constructor() {
        this.x = 0;
        this.y = 0;
    }
    update(value) {
        // logic
        this.y = value;
        return this;
    }
}

var x = new MyClass();
x = x.update(1);

之后使用console.log(x) 将再次导致y 成为0,而不是1

我知道setget,但我无法在update() 中执行任何逻辑或返回任何内容。

这是故意的,还是我完全做错了?

我想说明我正在使用 NodeJS

我正在做一些事情,例如:

class.js ->
    module.exports = /*class MyClass{}*/ (the above MyClass code)

app.js ->
    let MyClass = require('class');

    let x = new MyClass();
    x.update(1);

    console.log(x) (this returns the same value as x before calling update())

【问题讨论】:

  • 您的代码不应该工作,因为您缺少 class 关键字并且您不能将类调用为函数
  • 我无法重现您的问题:puu.sh/pOHGf/3f57163da1.png
  • @Kondax 你确定你检查的是x.y而不是x.x吗?
  • 是的,我正在检查 x.y。我将在操作中添加更多信息。
  • “这在调用 update() 之前返回与 x 相同的值”x 引用相同的值。 console.log(x.y) 的输出是什么?

标签: javascript node.js class ecmascript-6


【解决方案1】:

有效!

 var x =new MyClass();
    console.log(x.update(1)); //1
    console.log(x.y); //1

【讨论】:

    【解决方案2】:

    调用x.y 将导致0

    没有。这表明您的 // logic 存在缺陷。如果没有额外的逻辑,x.y 属性最终会变成1

    【讨论】:

    • 我的// logic 只检查value 的最小值和最大值,如果不满足则返回一个int。
    • @Kondax 那么检查最小值/最大值的逻辑可能总是成功。确定的唯一方法是发布代码。
    • @Kondax:这正是我要说的,这种逻辑可能很容易出错。也许是一个分配而不是与0的比较?
    • @Bergi 是的,我看过了,但没关系 - 只是 if a < b return c 等等。
    • @Kondax:好吧,return c 会阻止属性分配,例如……要么你发布你正在使用的确切代码,要么我们只能告诉你它不会发生。跨度>
    猜你喜欢
    • 2017-03-09
    • 2019-06-30
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 2015-02-16
    • 2018-05-11
    相关资源
    最近更新 更多