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 ?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With