Several ways to create general js objects

  • 2021-07-12 05:19:05
  • OfStack

1. Object literally creates an object

var obj = { a:1,b:2 };

Note: The object literal is an expression that creates and initializes a new object with each operation and evaluates each property value of the new object. Therefore, if you use the object literal in the loop body, a new object will be created every time you loop.

2. Create an object with 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 the constructor. The primitive types in js all contain built-in constructors, or you can define your own constructors.

3. Create an object by executing the function immediately

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

Note: Inside the immediate execution function, 1 must have an return statement, and the content of return 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. By passing in the prototype object, you can create an object that inherits this prototype object. For example, in the above example, the obj object inherits the x and y attributes.


Related articles: