this code
class Foo
bar: []
test = new Foo()
test.bar.push('b')
test2 = new Foo()
console.log test2.bar
Will produce output ['b']. How it is even possible?
This is what CoffeScript generates:
// 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);
And therefore is exactly true what is written below. Thank you guys.
bar is a single array instance that belongs to Foo.prototype.
new Foo().bar will always refer to this same array instance.
Therefore, any mutations performed through one Foo instance will also be visible thtough any other Foo instance.
The solution:
If you want Foo's to be created with this.bar = [], do it in the constructor:
class Foo
constructor: -> @bar = []