【问题标题】:Node.js class issue, or Am I doing something wrong? [duplicate]Node.js 类问题,还是我做错了什么? [复制]
【发布时间】:2013-06-03 21:04:42
【问题描述】:

这段代码

class Foo
  bar: []

test = new Foo()
test.bar.push('b')

test2 = new Foo()
console.log test2.bar

将产生输出['b']。怎么可能?

编辑:

这是 CoffeScript 生成的:

// Generated by CoffeeScript 1.4.0
var Test, test, test2;

Test = (function() {
  function Test() {}
  Test.prototype.a = [];
  return Test;
})();

test = new Test();
test.a.push('b');

test2 = new Test();
console.log(test2.a);

因此,下面写的完全正确。谢谢各位。

【问题讨论】:

  • 你用什么语言写的?
  • 如果原型上定义了bar,那么这是可能的。
  • @SLaks 这似乎是咖啡脚本
  • 我认为您将其设为“类”变量。
  • 抱歉,这是咖啡脚本

标签: node.js coffeescript


【解决方案1】:

bar 是属于Foo.prototype 的单个数组实例。
new Foo().bar 将始终引用此相同 数组实例。

因此,通过一个Foo 实例执行的任何突变也将通过任何其他Foo 实例可见。

解决办法:

永远不要在原型中放置可变状态。

【讨论】:

  • “永远不要将可变状态放入原型中。” - 正确地加粗。当我经验不足时,我被它咬了。 :)
【解决方案2】:

如果您希望使用this.bar = [] 创建Foo,请在构造函数中进行:

class Foo
  constructor: -> @bar = []

【讨论】:

  • 是的,我现在就是这样做的。我的错。 CoffeeScript 让我很困惑——在我看到生成的代码的那一刻,我很清楚。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-24
  • 2011-05-02
  • 2021-12-23
  • 2019-12-21
  • 1970-01-01
  • 2010-12-14
  • 1970-01-01
相关资源
最近更新 更多