In JavaScript, this
can sometimes trip us up. This is because the value of this
depends on the context in which it is being used.
When defining classes in CoffeeScript, instance methods will execute on the current this
context. For normally instantiated objects, this
refers to the object itself.
If the instance method is instead passed as a function callback, this
represents the object that is executing the callback.
For example, consider the following code:
class Person constructor: (@firstName, @lastName) -> displayFullName: -> console.log "#{@firstName} #{@lastName}" person = new Person('Tracy', 'Ouellette') person.displayFullName()
If you run this code, person.displayFullName()
will give the following output:
Tracy Ouellette
However, consider what would happen if you used person.deplayFullName()
as a callback:
func = (callback) -> callback() func(person.displayFullName)
Its output would be:
undefined undefined
What's going on here...