CoffeeScript Static Inheritance Property

Define this simple code:

class Foo
  @foo = 'blah'
  console.log(@foo)

class Bar extends Foo
  constructor: () ->
    console.log(@foo)

  bar: () ->
    console.log(@foo)

b = new Bar
b.bar()

And the result:

blah
undefined
undefined

How can I access @fooin an inherited class?

+3
source share
2 answers

Actually you want to write

console.log(@constructor.foo)

in the constructor Bar. (A working example is here .) @constructorPoints to a class ( Bar) that inherits static properties Foo. These properties are not in the instance, which means @from the constructor.

(Yes, it is strange that he @constructor, not @class, but because it obj.constructoris JavaScript-ism, and not the special CoffeeScript syntax.)

: @ . @ . . , CoffeeScript: JavaScript.

+5

foo foo, :

class Bar extends Foo
  constructor: () ->
    console.log(Foo.foo)
  bar: () ->
    console.log(Foo.foo)
+2

All Articles