In es6, the constructor is a special function that is mainly used to initialize objects, that is, to attach initial values to object member variables. The first letter of its function name is usually capitalized, and is always the same as new. use together. A function can only be used as a constructor when called with the new operator. If the new operator is not used, it is just an ordinary function.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
The constructor is a special function, mainly used to initialize objects, that is, to attach initial values to object member variables. It is always used with new. We can extract some public properties and methods from the object and encapsulate them into this function.
The first letter of the function name of the constructor is usually capitalized.
When called as a constructor, it must be used with the new operator. A function can only be used as a constructor when called with the new operator. If the new operator is not used, it is just an ordinary function.
When a function is used as a constructor, it can create an instance of the object through the new operator and call the corresponding function through the instance.
// 构造函数 function Person(name, age) { this.name = name; this.age = age; this.sayName = function () { alert(this.name); }; } var person = new Person('kingx', '12'); person.sayName(); // 'kingx'
When a function is used as a normal function, this inside the function will point to window.
Person('kingx', '12'); window.sayName(); // 'kingx'
Using the constructor, we can create the object instance we want at any time. The constructor will perform the following 4 steps when executed:
Created through the new operator A new object is created at a new address in memory.
Determine the pointer for this in the constructor.
Execute the constructor code and add attributes to the instance.
Return this newly created object.
Take the previous code to generate a person instance as an example:
Step one: Create a new address in memory for the person instance.
Step 2: Determine the this point of the person instance, pointing to the person itself.
Step 3: Add name, age and sayName attributes to the person instance, where the sayName attribute value is a function.
Step 4: Return this person instance.
Note: A sayName attribute is added to this in the constructor, and its value is a function, so that every time a new instance is created, a new one will be added to the instance. sayName attribute, and the sayName attribute is different in different instances.
【Related recommendations: javascript video tutorial, web front-end】
The above is the detailed content of what is a constructor in es6. For more information, please follow other related articles on the PHP Chinese website!