Effective JavaScript Item 31 takes precedence over object.getprototypeof instead of __proto__

Source: Internet
Author: User

this series as effective JavaScript 's reading notes.

in the ES5 introduced in the object.getprototypeof as a standard for getting object prototype objects API . However, in very many operating environments. also provides a special __proto__ attribute to achieve the same purpose.

since not all environments offer this __proto__ property, and each environment is implemented differently, some results may be inconsistent:


In some environments var is empty = Object.create (null); Object with no prototype "__proto__" in empty; False (in some environments)//var empty = Object.create (null) in some environments; Object with no prototype "__proto__" in empty; True (in some environments)

So when the environment supports object.getprototypeof method, use it preferentially.

Even if not supported. can also be implemented in order to achieve a:


if (typeof object.getprototypeof = = = "undefined") {object.getprototypeof = function (obj) {var t = typeof obj;if (!obj | | ( T!== "Object" && t!== "function") {throw new TypeError ("Not a object");} return obj.__proto__;};}

The code above first checks the current environment, assuming it has supported the object.getprototypeof , it will not be defined again and again.

In addition, when using __proto__ will cause some errors in the Item will be discussed in the.

Summarize:

  1. preferential use of standard methods object.getprototypeof . Instead of the nonstandard __proto__ property.

  2. for non- ES5 environment to achieve a object.getprototypeof method. This preserves the consistency of the code.

Effective JavaScript Item 31 takes precedence over object.getprototypeof instead of __proto__

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.