04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 7: Anonymous Functions<br />

a closure that accesses num is created and returned. Now each function in the result array has its own<br />

copy of num , and thus can return separate numbers.<br />

The this Object<br />

Using the this object inside closures introduces some problems. The this object is bound at runtime<br />

based on the context in which a function is executed: when used inside global functions, this is equal to<br />

window , whereas this is equal to the object when called as an object method. Anonymous functions are<br />

considered to be global in this context, so the this object always points to window . Due to the way<br />

closures are written, however, this fact is not always obvious. Consider the following:<br />

var name = “The Window”;<br />

var object = {<br />

name : “My Object”,<br />

};<br />

getNameFunc : function(){<br />

return function(){<br />

return this.name;<br />

};<br />

}<br />

alert(object.getNameFunc()()); //”The Window”<br />

Here, a global variable called name is created along with an object that also contains a property called<br />

name . The object contains a method, getNameFunc() , that returns an anonymous function, which<br />

returns this.name . Since getNameFunc() returns a function, calling object.getNameFunc()()<br />

immediately calls the function that is returned, which returns a string. In this case, however, it returns<br />

“ The Window ” , which is the value of the global name variable. Why didn ’ t the anonymous function pick<br />

up the containing scope ’ s this object?<br />

Remember that each function automatically gets two special variables in its activation object as soon as<br />

the function is called: this and arguments . An inner function can never access these variables from an<br />

outer function directly since the search for variables with these names stops on the inner function ’ s<br />

activation object (look back at Figure 7 - 2 for more information). It is possible to allow a closure access to<br />

a different this object by storing it in another variable that the closure can access, as in this example:<br />

var name = “The Window”;<br />

var object = {<br />

name : “My Object”,<br />

};<br />

getNameFunc : function(){<br />

var that = this;<br />

return function(){<br />

return that.name;<br />

};<br />

}<br />

alert(object.getNameFunc()()); //”My Object”<br />

189

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!