MonkeyBonkey
MonkeyBonkey

Reputation: 47871

what is the scope of "this" in coffeescript classes

I'm still confused by scope and the context of "this" in coffee script and javascript inheritance. Why is this(@) used for creating static methods as well as referencing instance methods, like the difference between @myStaticMethod and @move, what is "this" representing in both cases?

e.g.

class Animal

    @myStaticMethod : () ->
            console.log this is a static method
    move:(numberOfLegs) ->
        console.log numberOfLegs + ' legs moving'

    run: (numberOfLegs) ->
        @move(numberOfLegs)

class Dog extends Animal

    sprint: () ->
        return @run(4)

dog = new Dog()
dog.sprint()

Upvotes: 1

Views: 102

Answers (1)

Sergey Metlov
Sergey Metlov

Reputation: 26291

You have to call @run() because run() is the local function call.

class Dog extends Animal

sprint: () ->
    run = (x) ->
        alert x

    run(4)

From the other hand @run() is a this.run() JavaScript analog. As you use inheritance in you example then method run is extended to Dog from Animal and as a result moved to Dog's prototype. So you should call run from current object.

Why is this(@) used for creating static methods as well as referencing instance methods

@ signs are different in these 2 cases. In your example if you want to call static method you should write Animal.myStaticMethod() both inside and outside class. But when you need to call instance method inside class you use @ just like equivalent of this in JS.

Look at small example in CoffeeScript console. As you can see on the right side staticMethod is not added to prototype so it is not instance method and @ in this case has nothing common with @ in @instanceMethod().

Upvotes: 2

Related Questions