Using Object.create () to create objects in JavaScript introduce _javascript tips

Source: Internet
Author: User

In addition to the use of literal and new operators for object creation, Object.create () can also be used in the ECMAScript 5 standard. The Object.create () function accepts 2 objects as arguments: The first object is required, represents the prototype of the object being created, and the second object is optional, defining the properties of the object being created (for example, writable, enumerable).

Copy Code code as follows:

var o = object.create ({x:1, y:7});
Console.log (o);//object {x=1, y=7}
Console.log (o.__proto__);//object {x=1, y=7}

Calling Object.create () with NULL as the first argument generates an object without prototype that will not have any basic object attributes (for example, the + operator will throw an exception for this object because there is no ToString () method):

Copy Code code as follows:

var O2 = object.create (null);
Console.log ("It is" + O2);//type Error, can ' t convert O2 to primitive Type

For browsers that support only the ECMAScript 3 standard, you can use the Douglas Crockford method for Object.create () operations:

Copy Code code as follows:

if (typeof object.create!== ' function ') {
Object.create = function (o) {
function F () {}
F.prototype = O;
return new F ();
};
}
NewObject = Object.create (Oldobject);

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.