To determine that a property is defined in the object itself rather than inheriting from the prototype chain, we need to use Object.prototype
the inherited hasOwnProperty
method.
hasOwnProperty
Method is the Javascript
only one that handles object properties and does not traverse the prototype chain upwards.
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 the hasOwnProperty
correct answer can be given, which is necessary to traverse the properties of an object. Javascript
There is no other way to determine whether a property is defined in the object itself or inherited from the prototype chain.
hasOwnProperty as a property
Javascript
is not hasOwnProperty
set as a sensitive word, which means you can have a property named hasOwnProperty
. At this point 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 ({}). Hasownproperty.call (f Oo, ' bar '); true//It ' s also possible to use hasOwnProperty from the object//prototype for this PurposeObject.prototype.hasOwnProp Erty.call (foo, ' Bar '); True
Summarize
When judging the existence of an object property, hasOwnProperty
It is the only method that can be relied upon. It is also important to note that when we use it for in loop
to traverse objects, the use hasOwnProperty
will be a good way to avoid the problem of the expansion of the prototype object.
hasOwnProperty of JavaScript Object article