HTML and CSS Reference
In-Depth Information
In the preceding code, bobObj is an object with a method called sayPhrase . Like most OO languages,
you have a special keyword you can use to refer to the current object. Unlike most other languages, however,
the current object (generally called the context ) is much more malleable in JavaScript than in other languages.
For example:
var bobObj = {
phrase: "Yay!",
sayPhrase: function() { alert(this.phrase); }
// Will pop up an alert with "Yay!"
// Will pop up an alert with "undefined" after 100ms
setTimeout(bobObj.sayPhrase, 100);
In the first example, everything works as expected. The this keyword is bound to the object you expect,
bobObj . In the second example, however, the context of the function sayPhrase is lost because it is used as
in a callback. There are a couple of ways around this. This first is not to use the this keyword but to refer to
the object directly:
bobObj = {
phrase: "Yay!",
sayPhrase: function() { alert(bobObj.phrase); }
// Works correctly
setTimeout(bobObj.sayPhrase, 100);
This method is okay for one-off objects, but it is much more common to have many instances of an object, so
referring to the object explicitly isn't possible. (This issue can also be skirted with a design-pattern implemented
during object creation as discussed in Chapter 9, “Bootstrapping the Quintus Engine: Part I.”)
A second way around this is to use the jQuery proxy function to permanently bind the context:
bobObj = {
phrase: "Yay!",
sayPhrase: function() { alert(this.phrase); }
// Create a proxied function
var proxiedFunc = $.proxy(bobObj.sayPhrase, bobObj);
// Will pop up an alert with "Yay!" after 100ms
setTimeout(proxiedFunc, 100);
Any time proxiedFunc is called from now on, the this keyword will be bound to bobObj .
Underscore.js (discussed later in this chapter) also has a handy method that does the same thing. Using un-
derscore, the setTimeout could be rewritten as
var proxiedFunc = _.bind(bobObj.sayPhrase, bobObj)
Understanding the subtleties of callbacks is important in HTML5 game development because callbacks are
used frequently. Making certain you know how to pass functions and knowing the context of this at any given
time is essential.
Search WWH ::

Custom Search