The constructor in JS is parsed in detail

  • 2020-03-30 02:17:51
  • OfStack

In JavaScript, any valid function can be used as a constructor for an object, including both built-in and user-defined functions. Once the function is executed as a constructor, its internal this property references the function itself.

Typically, constructors do not return a value, they just initialize the object passed in by this pointer and return nothing. If a function returns a value, the returned object becomes the value of the new expression. Formally, the only difference between a function being executed as a constructor and a normal function is whether to use the new operator.

The above description actually has a more precise meaning, which is to divide the return value of a function if it has a return value into two types: 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 the function is constructed as a constructor with the new operator, the result of the operation is replaced by its return value. In this case, the this value in the constructor is lost and the returned object is replaced. Such as:


function test()
{
   this.a=10;
   return function()
   {
      return 1;
   }
}
alert m=new test();
var n=test();
alert(m);//Returns the closure after return
alert(n);//Returns the closure after return

The value of m is the same as the value of n, which is the closure returned by the test function, while the object of this reference and the assignment of this.a=10 are all discarded.

If the return value of a function is a value type, its return value is discarded when the function is constructed as a constructor with the new operator. The result of the new expression is still the object that this references.

function test()
{
   this.a=10;
    return 1;
}
alert m=new test();
var n=test();
alert(m)//Return [Object]
alert(n)//Returns 1.


Related articles: