Home > Web Front-end > JS Tutorial > body text

Detailed introduction to this and return in JavaScript constructor

巴扎黑
Release: 2017-09-18 09:40:30
Original
2013 people have browsed it

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
Copy after login

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
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!