鉴于这种
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 = {}