Understanding of constructors in JS
As the basis of prototype and prototype chain, we should first understand the constructor and its execution process to better help us learn the knowledge of prototype and prototype chain
1, What is a constructor
In JavaScript, a function called with the new keyword is called a constructor. The first letter of the constructor is generally capitalized (it can also be capitalized, but it is not standardized)
2, Why use constructors
To learn each concept, we should not only know what it is, but also know why and what kind of problems to solve.
For example, if we want to enter the personal information of each student in class 1, grade 1, we can create some objects, such as:
var p1 = { name: 'zs', age: 6, gender: 'male', hobby: 'basketball' }; var p2 = { name: 'ls', age: 6, gender: 'female', hobby: 'dancing' }; var p3 = { name: 'ww', age: 6, gender: 'female', hobby: 'singing' }; var p4 = { name: 'zl', age: 6, gender: 'male', hobby: 'football' }; // ...
Like the above, we can treat each student's information as an object. However, we will find that we repeatedly write a lot of meaningless code. Such as name, age, gender and hobby. If there are 50 students in this class, we have to write it 50 times.
At this time, the advantages of constructors are reflected. We found that although each student has the properties of name, gender and hobby, they are all different, so we pass these properties as parameters of the constructor. Since they are all first-year students and age is basically 6 years old, we can write to death and deal with them separately in case of special circumstances. At this point, we can create the following functions:
function Person(name, gender, hobby) { this.name = name; this.gender = gender; this.hobby = hobby; this.age = 6; }
After creating the above function, we can call through the new keyword, that is, create an object through the constructor.
var p1 = new Person('zs', 'male', 'basketball'); var p2 = new Person('ls', 'female', 'dancing'); var p3 = new Person('ww', 'female', 'singing'); var p4 = new Person('zl', 'male', 'football'); // ...
3, Constructor execution
Let's start with some basic concepts..
function Animal(color) { this.color = color; }
When a function is created, we don't know whether it is a constructor. Even if the function name is capitalized, as in the above example, we can't be sure. Only when a function is called with the new keyword can we say that it is a constructor. As follows:
var dog = new Animal("black");
Below, we only discuss the execution process of the constructor, that is, when it is called with the new keyword.
Let's take the Person above as an example.
function Person(name, gender, hobby) { this.name = name; this.gender = gender; this.hobby = hobby; this.age = 6; } var p1 = new Person('zs', 'male', 'basketball');
At this point, the constructor will perform the following procedures:
-
When called with the new keyword, a new memory space will be created, marked as an instance of Animal.
-
this inside the function body points to the memory
Through the above two steps, we can draw such a conclusion.
var p2 = new Person('ls', 'female', 'dancing'); // Create a new memory #f2 var p3 = new Person('ww', 'female', 'singing'); // Create a new memory #f3
Whenever an instance is created, a new memory space (#f2, #f3) will be created. When #f2 is created, this in the function body points to #f2, and when #f3 is created, this in the function body points to #f3.
(3) Execute the code in the function body
Through the above explanation, you can know that adding an attribute to this is equivalent to adding an attribute to an instance.
(4) this is returned by default
Since this inside the function body points to the newly created memory space, returning this by default is equivalent to returning the memory space by default, that is, the memory space in the above figure #f1. At this time, #f1 the memory space is accepted by the variable p1. In other words, the memory address saved by the variable p1 is #f1, and it is also marked as an instance of Person.
The above is the whole execution process of the constructor;
4, Return value of constructor
The last step in the constructor execution process is to return this by default. By implication, there are other cases of the return value of the constructor. Let's talk about the return value of constructors.
- The return value is not added manually. this is returned by default
function Person1() { this.name = 'zhangsan'; } var p1 = new Person1();
According to the above, let's review it again. First, when called with the new keyword, a new memory space #f11 is generated and marked as an instance of Person1; Next, this inside the function body points to the memory space #f11; Execute the code inside the function body; Since this inside the function body points to the memory space, which is received by the variable p1, p1 will have a name attribute with the attribute value of 'zhangsan'.
p1: { name: 'zhangsan' }
- Manually add a return value of the basic data type, and finally return this
function Person2() { this.age = 28; return 50; } var p2 = new Person2(); console.log(p2.age); // 28 p2: { age: 28 }
If the above is a call to an ordinary function, the return value is 50.
- Manually add the return value of a complex data type (object) and finally return the object
Chestnuts:
function Person3() { this.height = '180'; return ['a', 'b', 'c']; } var p3 = new Person3(); console.log(p3.height); // undefined console.log(p3.length); // 3 console.log(p3[0]); // 'a'
Another Chestnut:
function Person4() { this.gender = 'male'; return { gender: 'neutral' }; } var p4 = new Person4(); console.log(p4.gender); // 'neutral'
5, Must constructors be capitalized?
It is not necessary to use uppercase, but it is recommended to use uppercase if it is standardized
6, If you run the constructor directly without the new keyword, will there be an error? If there is no error, what is the difference between calling the constructor with new and not using new?
- Call the function using the new operator
Chestnuts:
function Person(name){ this.name = name; this.say = function(){ return "I am " + this.name; } } var person1 = new Person('nicole'); person1.say(); // "I am nicole"
When the constructor is called with new, the following changes will occur inside the function:
Create a this variable that points to an empty object. And the object inherits the prototype of the function;
Attributes and methods are added to the object referenced by this;
Implicitly return this object (if no other object is explicitly returned)
Use pseudo programs to show the above changes:
function Person(name){ // Create this variable to point to an empty object var this = {}; // Properties and methods are added to the object referenced by this this.name = name; this.say = function(){ return "I am " + this.name; } // Return this object return this; }
It can be seen that the biggest feature of calling the constructor with new is that this object points to the object generated by the constructor. Therefore, person1.say() will return the string: "I am nicole".
Tips:
If a return object is specified, the this object may be lost.
- Direct call function
If the function is called directly, the this object points to window, and no object is returned by default (unless the return value is explicitly declared).
Take the Person function as an example and call the Person function directly:
var person1 = Person('nicole'); person1; // undefined window.name; // nicole
- Summary
To prevent calling the constructor because you forget to use the new keyword, you can add some judgment conditions to forcibly call the new keyword. The code is as follows:
function Person(name){ if (!(this instanceof Person)) { return new Person(name); } this.name = name; this.say = function(){ return "I am " + this.name; } } var person1 = Person('nicole'); console.log(person1.say()); // I am nicole var person2 = new Person('lisa'); console.log(person2.say()); // I am lisa
Original author: laviniatu
Address: https://blog.csdn.net/sinat_21742529/article/details/83659459