0

考虑这个例子:

class Parent
  @staticMethod = ->
    #calleeConstructor = ????
    new calleeConstructor().x

class Child1 extends Parent
  constructor: ->
    @x = 10

class Child2 extends Parent
  constructor: ->
    @x = 20

#Usage
Child1.staticMethod() #Should return 10
Child2.staticMethod() #Should return 20

是否可以?

例如,我知道我可以从父实例方法访问原始类的其他一些静态成员或构造函数。我的意思是:

class Parent
  instanceMethod: -> @constructor.staticVar

class Child1 extends Parent
  @staticVar = 10

class Child2 extends Parent
  @staticVar = 20

#Usage
console.log new Child1().instanceMethod() #Should return 10
console.log new Child2().instanceMethod() #Should return 20
4

1 回答 1

2

在“类”方法中,@是类本身,因此您可以简单地说new @

class Parent
  @staticMethod = ->
    (new @).x

例如,给出这些:

class Child1 extends Parent
  constructor: (@x = 10) ->

class Child2 extends Parent
  constructor: (@x = 20) ->

class Child3 extends Child1
  constructor: (@x = 30) ->

你会得到这些结果:

Child1.staticMethod() # 10
Child2.staticMethod() # 20
Child3.staticMethod() # 30​​​​​​​​​​​​​​​​​​​

演示(请打开您的控制台):http: //jsfiddle.net/ambiguous/A6xjy/1/

于 2012-06-28T17:42:12.647 回答