Use Object. create () in JavaScript to create objects.

Source: Internet
Author: User

Use Object. create () in JavaScript to create objects.

In addition to the literal and new operators, you can use Object. create () to create an Object in the ECMAScript 5 standard. Object. the create () function accepts two objects as parameters: the first object is required, indicating the prototype of the created object. The second object is optional, defines the attributes of the created object (such as writable and enumerable ).

Copy codeThe Code is 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}

Use null as the first parameter to call the Object. create () will generate an Object without prototype, and the Object will not have any basic Object attributes (for example, because there is no toString () method, the + operator will throw an exception for this object ):

Copy codeThe Code is as follows:
Var o2 = Object. create (null );
Console. log ("It is" + o2); // Type Error, can't convert o2 to primitive type

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

Copy codeThe Code is as follows:
If (typeof Object. create! = 'Function '){
Object. create = function (o ){
Function F (){}
F. prototype = o;
Return new F ();
};
}
NewObject = Object. create (oldObject );

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.