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 necessary to traverse the properties of an object. There is no other way in Javascript to judge whether an attribute is defined in the object itself or inherited from the prototype chain.
hasOwnProperty as attributes
Javascript does not set hasOwnProperty as a sensitive word, which means you can have a property named hasOwnProperty. This time you can no longer use your own hasOwnProperty method to judge attributes, so you need to use an external hasOwnProperty method to make judgments.
var foo = {
hasownproperty:function () {return
false;
},
bar: ' Here is Dragons '
};
Foo.hasownproperty (' Bar '); Always returns false
//use another Object ' s hasownproperty and call it with ' this ' set to Foo
({}). hasownprope Rty.call (foo, ' Bar '); True
//It ' s also possible to use hasOwnProperty from the Object
//prototype for this purpose
Object.pro Totype.hasOwnProperty.call (foo, ' Bar '); True
Summarize
hasOwnProperty is the only method that can be relied upon to determine the existence of an object attribute. It is also important to note that when we use a for-in loop to traverse an object, using hasOwnProperty will be a good way to avoid the obsession caused by the extension of the prototype object.