Aleksandr Motsjonov
Aleksandr Motsjonov

Reputation: 1328

How to get original constructor from static method of parent class in CoffeeScript?

Consider this example:

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

Is it possible?

For example I know that I can access some other static members or constructor of original class from parent instance method. I mean this:

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

Upvotes: 0

Views: 130

Answers (1)

mu is too short
mu is too short

Reputation: 434685

Inside a "class" method, @ is the class itself so you can simply say new @:

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

For example, give these:

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

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

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

You'll get these results:

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

Demo (open your console please): http://jsfiddle.net/ambiguous/A6xjy/1/

Upvotes: 2

Related Questions