In JavaScript, any legal function can be used as an object constructor, which includes both built-in functions in the system and functions defined by the user. Once the function is executed as a constructor, this property inside it will refer to the function itself.
Generally speaking, constructors do not return values, they just initialize the object passed in by this pointer and return nothing. If a function has a return value, the returned object becomes the value of the new expression. From a formal point of view, the only difference between a function being executed as a constructor or an ordinary function, whether to use the new operator.
The above description actually has a more precise meaning. This requires the function to be divided into two cases: the return value of the function is the reference type and the value type.
If the return value of a function is data of a reference type (array, object, or function), then when this function executes construction with the new operator as a constructor, the result of the operation will be replaced by its return value. At this time, the constructor body is in the This value of , is lost, and is replaced by the returned object. For example:
The code copy is as follows:
function test()
{
this.a=10;
return function()
{
return 1;
}
}
alert m=new test();
var n=test();
alert(m);//Return the closure after return
alert(n);//Return the closure after return
The value of the running result m and n are the same, both are closures returned by the test function, and the object referenced by this and the assignment result of this.a=10 are all discarded.
If the return value of a function is a value type, then when the function performs construction using the new operator as a constructor, its return value will be discarded. The result of the new expression is still the object referenced by this.
The code copy is as follows:
function test()
{
this.a=10;
return 1;
}
alert m=new test();
var n=test();
alert(m)//Return [Object]
alert(n)//Return 1.