2

これを考えると

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クラスに属しています。コンストラクターに入れずにインスタンス変数を初期化するにはどうすればよいですか? そのようです:Aab

class A
   constructor: ->
      @opt = {}

編集:

スーパーコンストラクターが上書きされるため、継承が使用されている場合、これは問題になります。

class B
   constructor: ->
      console.log "i won't happen"
class A extends B
   constructor: ->
      console.log "i will happen"
      @opt = {}
4

3 に答える 3

1

super()さて、コンストラクターですべてのクラスメンバーを開始し、サブクラスコンストラクターを呼び出すことを忘れないでください...

    class B
       constructor: ->
          console.log "i will also happen"
    class A extends B
       constructor: ->
          super()
          console.log "i will happen"
          @opt = {}

    new A()
于 2012-09-19T12:05:00.090 に答える
0

「opt」が静的として機能する必要がある場合は、クラスにアタッチします

class A
    @opt: {}
    init: (param) ->
        # the rest is ommitted
于 2012-09-06T15:26:29.817 に答える