Does js constructor add new to object creation? js Constructor
Today I see this question:
Enter the content in "to do" TO make the following code support 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 constructor scope to a new object (so this points to this new object );
Execute the code in the constructor (add attributes for the new object );
Returns a new object.
Question 2: What will happen if the constructor is directly executed without the new operator?
Function Obj (name) {this. name = name; console. log (this); // in strict mode, the window object is undefined in non-strict mode.} var a = Obj ("name1"); console. log (a); // result => undefined
Oh, it turns out to be executed as a normal function call. Obj does not return a value, so a is undefined.
Differences between the two
Use the new operator to create an object. If the constructor does not return a value or the returned value is of the basic data type, the object is returned, as shown 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); // same as above
If the constructor returns a reference type:
function Obj(name){this.name = name;return {};}var b = new Obj;console.log(b); // {}
Summary
For constructor without adding new, the return value is the execution result of the constructor. For constructor execution with the new Keyword, if the return value is of the basic data type, this return value is ignored. If a reference type is returned, this reference type is returned.
So do you have the answer?
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 all about whether to add a new question to the js constructor object. If you have any questions after reading this article, please refer to the following message area for your support.