This article mainly gives you a detailed analysis of the problem of adding new or not adding new to the object created by the js constructor. If you are interested in this aspect, please refer to it.
I saw such a question today:
Fill in the content at "TO DO" so that the following code supports a.name = "name1"; b.name = "name2";
function Obj(name){ // TO DO } obj. /* TO DO */ = "name2"; var a = Obj("name1"); var b = new Obj;
Question 1: What does the new operator do?
Create a new object;
Assign the scope of the constructor to the new object (so this points to the new object);
Execute the constructor The code in (add properties to this new object);
returns the new object.
Question 2: What will happen if the constructor is executed directly without the new operator?
function Obj(name){ this.name = name; console.log(this); // 严格模式下是undefined 非严格模式下是window对象 } var a = Obj("name1"); console.log(a); // 结果 => undefined
Oh, it turns out that it is just executed as a normal function call. Obj has no return value, so a is undefined.
Summary of the difference between the two
Use the new operator to create an object, and the constructor has no return value or returns a basic data type, then the object is returned, as in the following example:
function Obj(name){ this.name = name; } var b = new Obj; console.log(b); // Obj { name: undefined } function Obj(name){ this.name = name; return 'chic'; } var b = new Obj; console.log(b); // 同上
If the constructor returns a reference type:
function Obj(name){ this.name = name; return {}; } var b = new Obj; console.log(b); // {}
Summary
For executing the constructor without adding new, the return value is the execution result of the constructor; for executing with the new keyword For constructors, if the return value is a basic data type, then the return value is ignored. If the return value is a reference type, then the reference type is returned.
So do you have the answer to the question?
Reference answer:
function Obj(name){ this.name = name; return this; } Obj.prototype.name = "name2"; var a = Obj("name1"); var b = new Obj;
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to implement the image preview function in the WeChat applet
How to use the image annotation component in jquery.picsign
How to package the koa2 framework app through webpack? What should I do?
Detailed interpretation of Vue component development ideas
The above is the detailed content of Regarding creating objects in js, should I add new?. For more information, please follow other related articles on the PHP Chinese website!