[Effective JavaScript note] 31st: Use the object.getprototypeof function instead of using the __proto__ property

Source: Internet
Author: User

ES5 introduced the Object.getprototypeof function as a standard API to get object prototypes, but many of the previous JS engines used a special __proto__ attribute to achieve the same goal. However, some browsers do not support this __proto__ property, so they are not fully compatible.
For example, for objects that have a null prototype, different environment results are different.

var empty=object.create (null); ' __proto__ ' in empty;//some environments will return false, others will return true

This leads to inconsistencies in the results, thus affecting the associated code that relies on this judgment.

In any case, the object.getprototypeof function is valid, and it is a more standard and portable method for extracting object prototypes. Because the __ptoto__ property pollutes all objects, it causes a large number of bugs.
For some JS environments that do not provide the ES5 API, it is easy to use the __proto__ property to implement the Object.getprototypeof function.

if (typeof object.getprototypeof = = = ' undefined ') {    object.getprototypeof=function (obj) {         var t=typeof obj;         if (!obj | | (t!== ' object ' && t!== ' function ')) {            throw new Error ("not an Object!) ");         }         return obj.__proto__;}    }

The above code determines whether the host environment implements the OBJECT.GETPROTOTYPEOF function and is safe in the ES5 standard environment.

Tips
    • Use standard-compliant object.getprototypeof functions instead of nonstandard __proto__ properties

    • Implementing object.getprototypeof functions in non-ES5 environments that support __proto__ properties

[Effective JavaScript note] 31st: Use the object.getprototypeof function instead of using the __proto__ property

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.