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 5: Reference Types<br />

This function ’ s syntax may look complicated, but essentially it ’ s just a function inside of a function,<br />

preceded by the return operator. The propertyName argument is accessible from the inner function<br />

and is used with bracket notation to retrieve the value of the given property. Once the property values<br />

are retrieved, a simple comparison can be done. This function can be used as in the following example:<br />

var data = [{name: “Zachary”, age: 28}, {name: “Nicholas”, age: 29}];<br />

data.sort(createComparisonFunction(“name”));<br />

alert(data[0].name); //Nicholas<br />

data.sort(createComparisonFunction(“age”));<br />

alert(data[0].name); //Zachary<br />

In this code, an array called data is created with two objects. Each object has a name property and an<br />

age property. By default, the sort() method would call toString() on each object to determine the<br />

sort order, which wouldn ’ t give logical results in this case. Calling createComparisonFunction<br />

( “ name “ ) creates a comparison function that sorts based on the name property, which means the first<br />

item will have the name “ Nicholas ” and an age of 29. When createComparisonFunction( “ age “ ) is<br />

called, it creates a comparison function that sorts based on the age property, meaning the first item will<br />

be the one with its name equal to “ Zachary ” and age equal to 28 .<br />

Function Internals<br />

Two special objects exist inside a function: arguments and this . The arguments object, as discussed in<br />

Chapter 3 , is an arraylike object that contains all of the arguments that were passed into the function.<br />

Though its primary use is to represent function arguments, the arguments object also has a property<br />

named callee , which is a pointer to the function that owns the arguments object. Consider the<br />

following classic factorial function:<br />

function factorial(num){<br />

if (num < = 1) {<br />

return 1;<br />

} else {<br />

return num * factorial(num-1)<br />

}<br />

}<br />

Factorial functions are typically defined to be recursive, as in this example, which works fine when the<br />

name of the function is set and won ’ t be changed. However, the proper execution of this function is<br />

tightly coupled with the function name “ factorial “ . It can be decoupled by using arguments<br />

.callee as follows:<br />

function factorial(num){<br />

if (num < = 1) {<br />

return 1;<br />

} else {<br />

return num * arguments.callee(num-1)<br />

}<br />

}<br />

126

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

Saved successfully!

Ooh no, something went wrong!