Coming from a C++/Java background, OOP-Inheritance in CoffeeScript got me confused.
Consider the following example:
class BaseClass
arr: []
addItem: (item) =>
@arr.push item
class SubClassA extends BaseClass
constructor: ->
@addItem("fromSubA")
class SubClassB extends BaseClass
console.log "Case 1"
instB = new BaseClass()
instA = new SubClassA()
console.log "instA: #{JSON.stringify instA.arr}"
console.log "instB #{JSON.stringify instB.arr}"
console.log "Case 2"
instB = new SubClassB()
instA = new SubClassA()
console.log "instA: #{JSON.stringify instA.arr}"
console.log "instB #{JSON.stringify instB.arr}"
console.log "Case 3"
instB = new SubClassB()
instA = new SubClassA()
console.log "instA: #{JSON.stringify instA.arr}"
console.log "instB #{JSON.stringify instB.arr}"
Output in tinkerbin.com:
Case 1
instA: ["fromSubA"]
instB ["fromSubA"]
Case 2
instA: ["fromSubA","fromSubA"]
instB ["fromSubA","fromSubA"]
Case 3
instA: ["fromSubA","fromSubA","fromSubA","Added manually, only to instB"]
instB ["fromSubA","fromSubA","fromSubA","Added manually, only to instB"]
Iow: the 'arr' instance-property of base-class behaves more or less like it's a static property; If I change the array in one instance, it's also changed in the other instance. Why is this array shared between instances?
Confusingly, a string property doesn't exhibit this behavior:
class BaseClass
property: "From Base"
class SubClassA extends BaseClass
constructor: ->
@property = "fromSubClassA"
class SubClassB extends BaseClass
document.write "Case 1<br>"
instB = new BaseClass()
instA = new SubClassA()
document.write "#{instA.property} <br>"
document.write "#{instB.property} <br><br>"
document.write "Case 2<br>"
instB = new SubClassB()
instA = new SubClassA()
instA.property = "test"
document.write "#{instA.property} <br>"
document.write "#{instB.property} <br>"
This code works just fine, keeping the 'property' property isolated between instances.
I'm clearly misunderstanding something here. What causes the array to become shared between instances?