Object of Javascript learning notes (III): hasOwnProperty _ basic knowledge-js tutorial

Source: Internet
Author: User
Tags hasownproperty
To determine whether an attribute is defined in the Object itself rather than inheriting from the prototype chain, we need to use the hasOwnProperty method inherited from Object. prototype. The hasOwnProperty method is the only method in Javascript that processes object attributes without traversing the prototype chain.
// 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 hasOwnProperty can give the correct answer, which is necessary to traverse the attributes of an object. No other method in Javascript can be used to determine whether an attribute is defined in the object itself or inherited from the prototype chain.

HasOwnProperty as a property

Javascript does not set hasOwnProperty as a sensitive word, which means you can have an attribute named hasOwnProperty. In this case, you cannot use its own hasOwnProperty Method to Determine the attributes. Therefore, you need to use the external hasOwnProperty Method to Determine the attributes.

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'); // true

Summary

If an object property exists, hasOwnProperty is the only method that can be depended on. We also want to remind you that when we use for in loop to traverse objects, using hasOwnProperty will avoid the troubles caused by the extension of prototype objects.

Related Article

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.