Book Image

CoffeeScript Application Development Cookbook

By : Mike Hatfield
Book Image

CoffeeScript Application Development Cookbook

By: Mike Hatfield

Overview of this book

Table of Contents (18 chapters)
CoffeeScript Application Development Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Dealing with the this keyword


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.

Getting ready

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...