Home > Article > Web Front-end > Javascript Study Notes - Objects (3): hasOwnProperty_Basic Knowledge
// Poisoning Object.prototype Object.prototype.bar = 1; var foo = {goo: undefined}; foo.bar; // 1 'bar' in foo; // true foo.hasOwnProperty('bar'); // false foo.hasOwnProperty('goo'); // true
Here, only hasOwnProperty can give the correct answer, which is very necessary when traversing the properties of an object. There is no other way in Javascript to tell whether a property is defined on the object itself or inherited from the prototype chain.
hasOwnProperty as property
Javascript does not make hasOwnProperty a sensitive word, which means you can have a property named hasOwnProperty. At this time, you can no longer use your own hasOwnProperty method to judge properties, so you need to use the external hasOwnProperty method to judge.
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 purpose Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
Summary
When determining the existence of object properties, hasOwnProperty is the only method that can be relied on. I would also like to remind you that when we use for in loop to traverse objects, using hasOwnProperty will effectively avoid the trouble caused by prototype object expansion.