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 6: Object-Oriented Programming<br />

Prototypes and the in Operator<br />

There are two ways to use the in operator: on its own or as a for - in loop. When used on its own, the in<br />

operator returns true when a property of the given name is accessible by the object, which is to say that<br />

the property may exist on the instance or on the prototype. Consider the following example:<br />

function Person(){<br />

}<br />

Person.prototype.name = “Nicholas”;<br />

Person.prototype.age = 29;<br />

Person.prototype.job = “Software Engineer”;<br />

Person.prototype.sayName = function(){<br />

alert(this.name);<br />

};<br />

var person1 = new Person();<br />

var person2 = new Person();<br />

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

alert(“name” in person1); //true<br />

person1.name = “Greg”;<br />

alert(person1.name); //”Greg” - from instance<br />

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

alert(“name” in person1); //true<br />

alert(person2.name); //”Nicholas” - from prototype<br />

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

alert(“name” in person2); //true<br />

delete person1.name;<br />

alert(person1.name); //”Nicholas” - from the prototype<br />

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

alert(“name” in person1); //true<br />

Throughout the execution of this code, the property name is available on each object either directly or<br />

from the prototype. Therefore, calling ” name ” in person1 always returns true , regardless of whether<br />

the property exists on the instance. It ’ s possible to determine if the property of an object exists on the<br />

prototype by combining a call to hasOwnProperty() with the in operator like this:<br />

function hasPrototypeProperty(object, name){<br />

return !object.hasOwnProperty(name) & & (name in object);<br />

}<br />

Since the in operator always returns true so long as the property is accessible by the object and<br />

hasOwnProperty() returns true only if the property exists on the instance, a prototype property can<br />

160

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

Saved successfully!

Ooh no, something went wrong!