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()
You have to call
@run()becauserun()is the local function call.From the other hand
@run()is athis.run()JavaScript analog. As you use inheritance in you example then methodrunis extended toDogfromAnimaland as a result moved toDog‘s prototype. So you should callrunfrom current object.@signs are different in these 2 cases. In your example if you want to call static method you should writeAnimal.myStaticMethod()both inside and outside class. But when you need to call instance method inside class you use@just like equivalent ofthisin JS.Look at small example in CoffeeScript console. As you can see on the right side
staticMethodis not added to prototype so it is not instance method and@in this case has nothing common with@in@instanceMethod().