Several methods for creating common js objects and js objects

Source: Internet
Author: User

Several methods for creating common js objects and js objects

1. Create an object literally

Var obj = {a: 1, B: 2 };

Note:An object literal is an expression that creates and initializes a new object and calculates each attribute value of the new object. Therefore, if the object literal volume is used in the loop body, a new object will be created every cycle.

2. Create an object using the new operator

Var obj = new Object (); // create an empty Object var ary = new Array (); // create an empty Array Object

Note:The new operator is followed by a function call, which is called a constructor. The original type in js contains built-in constructor, and you can also define the constructor yourself.

3. Create an object by executing the function immediately

Var obj = (function () {return {x: 1, y: 2 };}());

Note:You must have a return statement inside the function to be executed immediately. The returned content is the object to be created.

4. create an Object through Object. create ()

Var obj = Object. create ({x: 1, y: 2 });

Note:Object. create () is a static function. After passing in the prototype Object, you can create an Object that inherits the prototype Object. For example, in the preceding example, the obj Object inherits the x and y attributes.

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

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.