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 = []
- 我如何用咖啡脚本和ES6创build一个sails.js项目
- 编译Coffeescript时不要添加var
- coffeescript版本的string.format,sprintf()等javascript或node.js
- 我如何configurationpassport-github来确认callback用户?
- 从诺言结果导出节点模块
- Javascript代理:节点代理,和谐,混合对象与魔法getter和setter …在Coffeescript?
- 跨用户同步骨干模型状态的最简单方法是什么? Node.js的
- 没有findAngularJS快递咖啡资产控制器
- 如何在Locomotivejs中设置coffescript?