Given this
class A
opt: {}
init: (param) ->
console.log "arg is ", @opt.arg
@opt.arg = param
a = new A()
a.init("a")
console.log "first", a.opt.arg
b = new A()
b.init("b")
console.log "second", b.opt.arg
This is the output
arg is undefined
first a
arg is a
second b
The variable opt is acting as a static, it belongs to the class A instead of the instance a or b. How do I initialize instance variables without having to put them in a constructor? Like so:
class A
constructor: ->
@opt = {}
Edit:
This is problematic when inheritance is used since the super constructor is overwritten.
class B
constructor: ->
console.log "i won't happen"
class A extends B
constructor: ->
console.log "i will happen"
@opt = {}
Your opt object is shared via the prototype, you can override it in instances directly, but if you change objects inside it, you actually change the prototype object (static like behavior). It’s very important to understand prototypes when using coffeescript classes.
I think the best way to init instance members is in the constructor like you are doing atm.