Node.js类的问题,或者我做错了什么?
这个代码
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
是属于Foo.prototype
的单个数组实例。
new Foo().bar
将始终引用这个相同的数组实例。
因此,通过一个Foo
实例执行的任何突变也将在任何其他Foo
实例中可见。
解决scheme:
永远不要把可变状态放在原型中。
如果你想要用this.bar = []
创buildFoo
,可以在构造函数中完成:
class Foo constructor: -> @bar = []