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

be determined if the in operator returns true but hasOwnProperty() returns false . Consider the<br />

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 person = new Person();<br />

alert(hasPrototypeProperty(person, “name”)); //true<br />

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

alert(hasPrototypeProperty(person, “name”)); //false<br />

In this code, the name property first exists on the prototype, so hasPrototypeProperty() returns true .<br />

Once the name property is overwritten, it exists on the instance, so hasPrototypeProperty() returns<br />

false .<br />

When using a for - in loop, all properties that are accessible by the object and can be enumerated will be<br />

returned, which includes properties on both the instance and on the prototype. Instance properties that<br />

shadow a nonenumerable prototype property (a property that has [[DontEnum]] set) will be returned<br />

in the for - in loop since all developer - defined properties are enumerable by rule, except in Internet<br />

Explorer (IE).<br />

The IE implementation of JScript has a bug where properties that shadow nonenumerable properties will<br />

not show up in a for - in loop. Here ’ s an example:<br />

var o = {<br />

toString : function(){<br />

return “My Object”;<br />

}<br />

};<br />

for (var prop in o){<br />

if (prop == “toString”){<br />

alert(“Found toString”);<br />

}<br />

}<br />

//won’t display in Internet Explorer<br />

When this code is run, a single alert should be displayed indicating that the toString() method was<br />

found. The object o has an instance property called toString() that shadows the prototype ’ s<br />

toString() method (which is not enumerable). In IE, this alert is never displayed because it skips over<br />

the property, honoring the [[DontEnum]] flag that was set on the prototype ’ s toString() method. This<br />

same bug affects all properties and methods that aren ’ t enumerable by default: hasOwnProperty() ,<br />

propertyIsEnumerable() , toLocaleString() , toString() , and valueOf() . Some browsers set<br />

[[DontEnum]] on the constructor and prototype properties, but this is inconsistent across<br />

implementations.<br />

161

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

Saved successfully!

Ooh no, something went wrong!