これを考えると
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
これが出力です
arg is undefined
first a
arg is a
second b
変数は静的として機能しており、インスタンスまたはではなくopt
クラスに属しています。コンストラクターに入れずにインスタンス変数を初期化するにはどうすればよいですか? そのようです:A
a
b
class A
constructor: ->
@opt = {}
編集:
スーパーコンストラクターが上書きされるため、継承が使用されている場合、これは問題になります。
class B
constructor: ->
console.log "i won't happen"
class A extends B
constructor: ->
console.log "i will happen"
@opt = {}