Home >Web Front-end >JS Tutorial >Detailed analysis of constructors in JS_javascript skills
In JavaScript, any legal function can be used as the constructor of an object, including both system built-in functions and user-defined functions. Once a function is executed as a constructor, its internal this attribute will refer to the function itself.
Generally speaking, constructors have no return value, they just initialize the object passed in by the this pointer and return nothing. If a function returns a value, the returned object becomes the value of the new expression. From a formal point of view, the only difference between whether a function is executed as a constructor or an ordinary function is whether the new operator is used.
The above description actually has a more precise meaning, which divides the situation where the function returns a value into two situations: the return value of the function is a reference type and a value type.
If the return value of a function is data of a reference type (array, object or function), then when this function is constructed using the new operator as a constructor, the result of the operation will be replaced by its return value. At this time, the this value in the constructor body is lost and replaced by the returned object. For example: