Execution Context

JavaScript has two special objects that are created every time a function is called: this and arguments. I mentioned arguments once before, in Splatted Arguments, and I won’t mention it again. But this is part of JavaScript’s core essence. It allows functions to be used as methods, meaning that they can be attached to an object and know which object they’re attached to. Here’s a simple example:

 fry = {}
 fry.name = ​'Philip J. Fry'
 fry.sayName = -> console.log(​this​.name)
 fry.sayName()
 Philip J. Fry

The magic here is that JavaScript and CoffeeScript read the statement fry.sayName() to mean “call the function fry.sayName in the context of fry.” The fact that we assigned the function to fry.sayName as soon as we defined ...

Get CoffeeScript, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.