3

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 ?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

And if I want to access to @foo from another method than the constructor ?
I've modified my question to reflect this.
The answer is the same. b.bar() calls that method in the context of b, so @constructor will point to the Bar class. Working example. I would, again, refer you to my book for a clearer understanding of how @/this works.
I will definitively look into buying your book. T hanks for this answer !
2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.