hasOwnProperty of JavaScript Object article

Source: Internet
Author: User
Tags hasownproperty

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.
hasOwnPropertyMethod 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. JavascriptThere 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

Javascriptis 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

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.