This article introduces you to this and return in the JS constructor through example code. Friends who need it can refer to it.
Look at a piece of code first,
function Foo(name,age){ this.name=name; this.age=age; } var foo=new Foo("Tom",14); foo.name;//Tom foo.age;//14
Use the constructor to instantiate the process that occurs:
1. Create an empty object of foo.
2. Point this of Foo in the constructor to the object foo.
3. The _proto_ attribute of foo points to the prototype prototype of the Foo function.
4. Execute the code in the constructor.
Compared with ordinary functions, this in the constructor points to the instance, while this in ordinary function calls points to windows.
If return is added to the constructor, there are two situations
function Foo(name,age){ this.name=name; this.age=age; return {name:"Jeff"} } var foo=new Foo("Tom",14); foo.name;//Jeff
1. Return is five simple data types: String , Number, Boolean, Null, Undefined.
In this case, ignore the return value and still return the this object.
2.Return is Object.
In this case, the this object is no longer returned, but the return value of the return statement is returned.
The above is the detailed content of Detailed introduction to this and return in JavaScript constructor. For more information, please follow other related articles on the PHP Chinese website!