// Poisoning Object.prototypeObject.prototype.bar = 1;var foo = {goo: undefined};foo.bar; // 1'bar' in foo; // truefoo.hasOwnProperty('bar'); // falsefoo.hasOwnProperty('goo'); // trueHere, only hasOwnProperty can give the correct answer, which is very necessary when it comes to traversing the properties of an object. There is no other way in Javascript to tell whether an attribute is defined in the object itself or inherited from the prototype chain.
hasOwnProperty as property
Javascript does not set hasOwnProperty as a sensitive word, which means you can have a property named hasOwnProperty. At this time, you can no longer use your hasOwnProperty method to judge properties, so you need to use the external hasOwnProperty method to make judgments.
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'); // trueSummarize
When judging that the object attribute exists, hasOwnProperty is the only method that can be relied on. Here we also want to remind you that when we use for in loop to traverse objects, using hasOwnProperty will be good at avoiding the troubles caused by prototype object extensions.
The following are the additions from other netizens:
hasOwnProperty() on the Object object prototype in Javascript is used to determine that a property is defined in the object itself rather than inherited from the prototype chain.
obj.hasOwnProperty(prop)
Parameter prop
The attribute string name or Symbol (ES6) to be detected
o = new Object();o.prop = 'exists';o.hasOwnProperty('prop'); // Return trueo.hasOwnProperty('toString'); // Return falseo.hasOwnProperty('hasOwnProperty'); // Return falseUse hasOwnProperty as the property name of an object
Because javascript does not use hasOwnProperty as a sensitive word, it is very likely that we will name one property of the object as hasOwnProperty, so that we can no longer use the hasOwnProperty method of the object prototype to determine whether the property is from the prototype chain.
var foo = { hasOwnProperty: function() { return false; }, bar: 'Here be dragons'};foo.hasOwnProperty('bar'); // Always return falseHow to solve this problem by not using this object.hasOwnProperty method? We need to use the real hasOwnProperty method on the prototype chain:
({}).hasOwnProperty.call(foo, 'bar'); // true// Or: Object.prototype.hasOwnProperty.call(foo, 'bar'); // trueReference: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty