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

Here, the person object is used as the prototype of two new objects. Initially, anotherPerson and<br />

yetAnotherPerson have only properties referenced from person (their prototype). You can overwrite<br />

the name property so each has its own name property and is no longer using person.name , but all<br />

instances share the same friends property, so changes made through one object affect all others.<br />

By providing a second argument to Object.create() , you can also add new properties to the<br />

created object. Consider the following:<br />

var person = {<br />

name: “Nicholas”,<br />

friends: [“Shelby”, “Court”, “Van”]<br />

};<br />

var anotherPerson = Object.create(person, {<br />

name: {<br />

value: “Greg”<br />

}<br />

});<br />

alert(anotherPerson.hasOwnProperty(“name”));<br />

anotherPerson.friends.push(“Rob”);<br />

//true<br />

In this example, the anotherPerson object is created by using Object.create() and passing in a<br />

second argument. The resulting object still has its own name property and doesn ’ t use the one on<br />

the prototype. This property was created as its descriptor was specified in the second argument. The<br />

Object.create() method is therefore ideal for prototypal inheritance of individual objects (as opposed<br />

to objects based on custom constructors).<br />

The second method for creating objects is Object.clone() . This method accepts a single argument,<br />

which is the object to clone, and returns an object. The returned object is a clone of the original in that its<br />

has the same prototype and the same instance properties. Here is an example:<br />

var person = {<br />

name: “Nicholas”,<br />

age: 29<br />

};<br />

var employee = Object.create(person, {<br />

job: {<br />

value: “Software Engineer”<br />

}<br />

});<br />

var employee2 = Object.clone(employee);<br />

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

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

alert(employee.hasOwnProperty(“job”)); //true<br />

alert(employee2.hasOwnProperty(“job”)); //true<br />

alert(employee.getPrototypeOf() === employee2.getProtoypeOf());<br />

//true<br />

This code creates a clone of the employee object and stores it in a variable named employee2 . This<br />

new object has the same prototype, person , as the original employee object and also has an instance<br />

property called job . Note that employee.job and employee2.job are not related to one another and<br />

are both instance properties of their respective objects.<br />

745

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

Saved successfully!

Ooh no, something went wrong!