如何从CoffeeScript中的父类的静态方法获取原始构造函数?

时间:2012-06-28 08:31:51

标签: coffeescript

考虑这个例子:

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

1 个答案:

答案 0 :(得分: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/