Home > Web Front-end > JS Tutorial > Detailed analysis of constructors in JS_javascript skills

Detailed analysis of constructors in JS_javascript skills

WBOY
Release: 2016-05-16 16:56:17
Original
1138 people have browsed it

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:

Copy code The code 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 sum of the operation result m The value of n is the same, it is the closure 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 is constructed 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.
Copy code The code 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.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template