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
in
Bar‘s constructor. (Working example here.)@constructorpoints to the class (Bar), which inherits the static properties ofFoo. Those properties aren’t on the instance, which is what@points to from the constructor.(Yes, it’s weird that it’s
@constructorrather than@class, but that’s becauseobj.constructoris 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.