Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static property inheritance CoffeeScript

Tags:

coffeescript

Let's 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 result is :

blah
undefined
undefined

How can I access @foo in inherited class ?

like image 407
magnetik Avatar asked Jun 13 '26 14:06

magnetik


2 Answers

You actually want to write

console.log(@constructor.foo)

in Bar's constructor. (Working example here.) @constructor points to the class (Bar), which inherits the static properties of Foo. Those properties aren't on the instance, which is what @ points to from the constructor.

(Yes, it's weird that it's @constructor rather than @class, but that's because obj.constructor is a JavaScript-ism, not a special CoffeeScript syntax.)

To clarify further: In the class body, @ points to the class. In the constructor, @ points to the instance. Hence the apparent inconsistency. I devote a lot of time to this in the chapter on classes in my book, CoffeeScript: Accelerated JavaScript Development.

like image 124
Trevor Burnham Avatar answered Jun 18 '26 01:06

Trevor Burnham


foo is a property of the Foo constructor, not its prototype:

class Bar extends Foo
  constructor: () ->
    console.log(Foo.foo)
  bar: () ->
    console.log(Foo.foo)
like image 43
Ricardo Tomasi Avatar answered Jun 18 '26 01:06

Ricardo Tomasi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!