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

literals have become a preferred way of passing a large number of optional arguments to a function, such<br />

as in this example:<br />

function displayInfo(args) {<br />

var output = “”;<br />

if (typeof args.name == “string”){<br />

output += “Name: “ + args.name + “\n”;<br />

}<br />

if (typeof args.age == “number”) {<br />

output += “Age: “ + args.age + “\n”;<br />

}<br />

}<br />

alert(output);<br />

displayInfo({<br />

name: “Nicholas”,<br />

age: 29<br />

});<br />

displayInfo({<br />

name: “Greg”<br />

});<br />

Here, the function displayInfo() accepts a single argument named args . The argument may come in<br />

with a property called name or age , or both or neither of those. The function is set up to test for the<br />

existence of each property using the typeof operator and then to construct a message to display based<br />

on their availability. This function is then called twice, each time with different data specified in an object<br />

literal. The function works correctly in both cases.<br />

This pattern for argument passing is best used when there is a large number of optional arguments that<br />

can be passed into the function. Generally speaking, named arguments are easier to work with but can<br />

get unwieldy when there are numerous optional arguments. The best approach is to use named<br />

arguments for those that are required, and an object literal to encompass multiple optional arguments.<br />

Although object properties are typically accessed using dot notation, which is common to many object -<br />

oriented languages, it ’ s also possible to access properties via bracket notation. When you use bracket<br />

notation, a string containing the property name is placed between the brackets, as in this example:<br />

alert(person[“name”]);<br />

alert(person.name);<br />

//”Nicholas”<br />

//”Nicholas”<br />

Functionally, there is no difference between the two approaches. The main advantage of bracket notation<br />

is that it allows you to use variables for property access, such as in this example:<br />

var propertyName = “name”;<br />

alert(person[propertyName]);<br />

//”Nicholas”<br />

Generally speaking, dot notation is preferred unless variables are necessary to access properties<br />

by name.<br />

99

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

Saved successfully!

Ooh no, something went wrong!