Using Object. create () in JavaScript to create objects _ javascript tips-js tutorial

Source: Internet
Author: User
This article mainly introduces how to use Object in JavaScript. create () describes how to create an object. This article first explains the syntax and then describes how to create an instance. If you want to create an object, refer to create an object. In addition to using the literal and new operators, in the ECMAScript 5 standard, you can also use Object. create. 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 ).

The 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 ):

The 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:

The 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.