JS constructor analysis

1. What is the constructor?

Function invoked with the new keyword

The main function is to initialize the object constructor, and new features are used together. that is, to create new objects from scratch, the constructor is to add properties and methods for the object, initialized. When the constructor is defined capitalized (specification).

2. Why use a constructor?

When you give a statement objects properties and methods, we can use var and let to a simple statement, but if we want to declare many variables, properties and methods are converging, when we need to reduce duplication meaningless code, save time, improve efficiency

code show as below:

var p1 = { name: 'zs', age: 6, gender: '男', hobby: 'basketball' }; var p2 = { name: 'ls', age: 6, gender: '女', hobby: 'dancing' }; var p3 = { name: 'ww', age: 6, gender: '女', hobby: 'singing' }; var p4 = { name: 'zl', age: 6, gender: '男', hobby: 'football' };

构造函数后:
function Person(name, gender, hobby) { this.name = name; this.gender = gender; this.hobby = hobby; this.age = 6; }

And then to call it by the new keyword:
var p1 = new Person('zs', '男', 'basketball'); var p2 = new Person('ls', '女', 'dancing'); var p3 = new Person('ww', '女', 'singing'); var p4 = new Person('zl', '男', 'football');

Imparting an initial value and a method of using new property, it can be done with pick, to avoid duplication of code write, take up memory.

3, during the execution of the constructor

only when a function to  newtime keyword to call, we can say that it is a constructor. Like this:
function Animal(color) { this.color = color; }
var dog = new Animal("black");

Below we discuss only during the execution of the constructor, it is based on  new a keyword to call.

We were still above Person example.

function Person(name, gender, hobby) { this.name = name; this.gender = gender; this.hobby = hobby; this.age = 6; } var p1 = new Person('zs', '男', 'basketball');
(1) When to  new keyword called, will create a new memory space, marked as instances of Person.

 

 Inside (2) member function  this points to the memory

 

 

Through the above two steps, we can conclude that.

var p2 = new Person('ls', '女', 'dancing'); // 创建一个新的内存 #f2 var p3 = new Person('ww', '女', 'singing'); // 创建一个新的内存 #f3 

Whenever you create an instance of the interior of the time, it will create a new memory space (# f2, # f3), # f2 created when the inside of the body of the function this point # f2, create # f3 when this function body point # f3.

(3) executing the function code in vivo

Through the above explanation, you know, add to this property, it is equivalent to add an instance property.

(4) default return this.

由于函数体内部的 this 指向新创建的内存空间,默认返回 this ,就相当于默认返回了该内存空间,也就是上图中的 #f1。此时,#f1的内存空间被变量 p1 所接受。也就是说 p1 这个变量,保存的内存地址就是 #f1,同时被标记为 Person 的实例。

以上就是构造函数的整个执行过程。



Guess you like

Origin www.cnblogs.com/jayfeng/p/12074096.html