To determine whether an attribute is defined in the Object itself rather than inheriting from the prototype chain, we need to use the hasOwnProperty method inherited from Object. prototype. The hasOwnProperty method is the only method in Javascript that processes object attributes without traversing the prototype chain.
// Poisoning Object.prototypeObject.prototype.bar = 1;var foo = {goo: undefined};foo.bar; // 1'bar' in foo; // truefoo.hasOwnProperty('bar'); // falsefoo.hasOwnProperty('goo'); // true
Here, only hasOwnProperty can give the correct answer, which is necessary to traverse the attributes of an object. No other method in Javascript can be used to determine whether an attribute is defined in the object itself or inherited from the prototype chain.
HasOwnProperty as a property
Javascript does not set hasOwnProperty as a sensitive word, which means you can have an attribute named hasOwnProperty. In this case, you cannot use its own hasOwnProperty Method to Determine the attributes. Therefore, you need to use the external hasOwnProperty Method to Determine the attributes.
var foo = { hasOwnProperty: function() { return false; }, bar: 'Here be dragons'};foo.hasOwnProperty('bar'); // always returns false// Use another Object's hasOwnProperty and call it with 'this' set to foo({}).hasOwnProperty.call(foo, 'bar'); // true// It's also possible to use hasOwnProperty from the Object// prototype for this purposeObject.prototype.hasOwnProperty.call(foo, 'bar'); // true
Summary
If an object property exists, hasOwnProperty is the only method that can be depended on. We also want to remind you that when we use for in loop to traverse objects, using hasOwnProperty will avoid the troubles caused by the extension of prototype objects.