Reputation: 1305
I am new to CoffeeScript (and rather inexperienced with JS too; so sorry if this is naive) and I was trying to create a class as below:
class Test
a: []
make: ->
@a.push ['A', 'B', 'C']
getdata: ->
output = ""
for i in @a
output += i
output
b = new Test
b.make()
alert(b.getdata())
c = new Test
c.make()
alert(c.getdata())
The output I get is: "A, B, C" "A, B, C, A, B, C"
Despite create a new instance of 'Test'; the array gets appended over and is not cleared. What am I doing wrong here? Am I initializing the member variable wrong?
Upvotes: 11
Views: 4375
Reputation: 129775
When you define a: []
, you're creating a single array object on the class prototype. Each instance of the class that you create will have this same array object. Whenever one instance modifies the value, the change is visible to all the others.
Note that this is only the case if you modify a value, such as by adding items to an array. If you replace the value, for example by assigning a new array, this will only affect the current instance.
When you want a property that's initialized on a per-instance basis you should to define it in the constructor
, when the instance is actually created:
class Test
constructor: ->
@a = []
@a.push ['A', 'B', 'C']
getdata: ->
output = ""
for i in @a
output += i
output
b = new Test
alert(b.getdata())
c = new Test
alert(c.getdata())
Try this out and you'll find that it works like you want.
Upvotes: 23