2

这段代码

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

因此,下面写的完全正确。感谢你们。

4

2 回答 2

3

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

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

解决方案:

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

于 2013-06-07T14:07:59.780 回答
0

如果要Foo使用 's 创建this.bar = [],请在构造函数中执行:

class Foo
  constructor: -> @bar = []
于 2013-06-07T14:24:23.157 回答