JavaScript Learning Notes Object Chapter (III): Hasownproperty_ basic knowledge

Source: Internet
Author: User
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.

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.