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 22: The Evolution of JavaScript<br />

and [[Flexible]] attributes on each property to false . You can determine if an object is frozen by<br />

using the Object.isFrozen() method and passing in the object. Any objects that are frozen are also<br />

considered to be sealed and non - extensible, so Object.isSealed() will return true and<br />

Object.isExtensible() will return false . Consider the following example:<br />

var person = {<br />

name: “Nicholas”,<br />

age: 29<br />

};<br />

alert(Object.isSealed(person)); //false<br />

Object.freeze(person);<br />

alert(Object.isFrozen(person)); //true<br />

alert(Object.isSealed(person)); //true<br />

alert(Object.isExtensible(person)); //false<br />

alert(delete person.name); //false<br />

alert(person.name); “Nicholas”<br />

person.name = “Michael”;<br />

alert(person.name); “Nicholas”<br />

In this example, the person object is frozen, so there is no way to add, delete, or change any properties.<br />

The attempt to delete person.name fails as does the attempt to change its value, which fails silently.<br />

Freezing an object ensures that it cannot be changed again during the lifetime of the program.<br />

Once an object is locked down in any of the three ways, it is locked down until the<br />

object goes out of scope. You cannot programmatically undo a lock down.<br />

Changes to Functions<br />

ECMAScript 3.1 includes several changes to functions in order to make them easier to use and debug.<br />

To begin, the language now natively supports function currying (as discussed in Chapter 18 ) through the<br />

addition of a bind() method on each function. This method accepts a variable number of arguments<br />

where the first argument becomes the value of this , and each subsequent argument becomes a bound<br />

argument. The bind() method works in the same way as the last version of the bind() function in<br />

Chapter 18. Here’s an example :<br />

var person = {<br />

name: “Nicholas”,<br />

age: 29<br />

};<br />

function sayName(){<br />

alert(this.name);<br />

}<br />

var boundSayName = sayName.bind(person);<br />

boundSayName(); //”Nicholas”<br />

This code creates a function called sayName() that references the this object. You can create a version of<br />

the function that is bound to the variable person by calling sayName.bind(person) . The returned<br />

function can then be called directly without any arguments. The bind() method has already been<br />

implemented natively in Chrome and is scheduled to be included in Firefox 3.1.<br />

748

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

Saved successfully!

Ooh no, something went wrong!