Reputation: 4431
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 ?
Upvotes: 3
Views: 1655
Reputation: 35253
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)
Upvotes: 2
Reputation: 77416
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.
Upvotes: 5