04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 7: Anonymous Functions<br />

contains a reference to the activation object for createComparisonFunction() . Figure 7 - 2 illustrates<br />

this relationship when the following code is executed:<br />

var compare = createComparisonFunction(“name”);<br />

var result = compare({ name: “Nicholas” }, { name: “Michael” });<br />

When the anonymous function is returned from createComparisonFunction() , its scope chain has<br />

been initialized to contain its own activation object, the activation object from<br />

createComparisonFunction() , and the global variable object. This gives the anonymous function<br />

access to all of the variables from createComparisonFunction() . Another interesting side effect is that<br />

the activation object from createComparisonFunction() cannot be destroyed once the function<br />

finishes executing because a reference still exists in the anonymous function ’ s scope chain. After<br />

createComparisonFunction() completes, its scope chain is destroyed but its activation object will<br />

remain in memory until the anonymous function is destroyed, as in the following:<br />

//create function<br />

var compareNames = createComparisonFunction(“name”);<br />

//call function<br />

var result = compareNames({ name: “Nicholas” }, { name: “Greg”});<br />

//dereference function - memory can now be reclaimed<br />

compareNames = null;<br />

Here, the comparison function is created and stored in the variable compareNames . Setting<br />

compareNames equal to null dereferences the function and allows the garbage collection routine to<br />

clean it up. The scope chain will then be destroyed and all of the scopes (except the global scope) can be<br />

destroyed safely. Figure 7 - 2 shows the scope - chain relationships that occur when compareNames() is<br />

called in this example.<br />

createComparisonFunction<br />

[[Scope]]<br />

Scope Chain<br />

1<br />

0<br />

Global Scope<br />

this<br />

createComparisonFunction<br />

result<br />

window<br />

undefined<br />

(anonymous)<br />

[[Scope]]<br />

Figure 7 - 2<br />

Scope Chain<br />

2<br />

1<br />

0<br />

createComparisonFunction Scope<br />

this<br />

window<br />

arguments<br />

["name"]<br />

propertyName<br />

"name"<br />

(anonymous) Scope<br />

this<br />

window<br />

arguments<br />

[]<br />

object1<br />

undefined<br />

object2<br />

undefined<br />

187

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

Saved successfully!

Ooh no, something went wrong!