Getting our context right
Now that we're starting to deal with classes a lot in our application, it's only a matter of time before we run into problems with context. When dealing with standalone functions, it's fairly easy to understand what data the function body sees. It knows about globals, variables defined within the function, and any variables that were present in the local scope when the function was defined. When methods are attached to objects, the question becomes a little more complicated. We'll look at one of the common sources of problems with object methods, and then we'll see how CoffeeScript can help us.
Let's make a simple class:
class Boat liftAnchor: (doneCallback) -> console.log "Lifting anchor." setSpeed: (speed) -> console.log "Adjusting speed to #{speed} knots." depart: -> @liftAnchor() @setSpeed 10
This works great if we wish to depart immediately:
caravel = new Boat caravel.depart()
However, raising the anchor doesn't happen immediately...