In JavaScript, the new operator can be used to create an object. How does the system use the new operator to create an object? Let's take a look at the process:
- First, define a class;
- Use the new operator to follow the function you defined to create a new class instance;
- Once the Javascript compiler encounters the new operator, it creates an empty instance variable and copies all prototype attributes and methods in the class to this instance, point all this in the member function to the newly created instance;
- Next, execute the function that follows the new operator;
- When you execute this function, if you try to assign a value to a non-existent attribute, the Javascript compiler will automatically create this attribute for you within this range;
- After the function is executed, the initialized instance is returned.
That is to say:
Javascript actually performs the following three processes when using new:
- Create an empty object;
- Copy the attributes and methods in the class prototype to the instance;
- Use the null object created in step 1 as the class parameter to call the class constructor.
Example 1: Simulate new
Description: Creates a class person, creates two variables P1 and P, and compares the final results of the two variables.
Although new is not used in the process of creating Variable P, it is the same as P1. See:
Example 2: Heavy Load
Description: There is a showname method in the class person. Person constructor. There is a showname Method on person. Prototype. which method is called by the instance?
A: Call the showname method in the person class.
The person class is defined as follows:
Function person (name, age ){This. Name = Name;This. Age = age;This. Showname = function () {alert ("This is the showname In the constructor:"+This. Name) ;}} person. Prototype = {showname: function () {alert ("This is the showname in prototype:"+This. Name) ;}, showage: function () {alert (This. Age );}}
Instantiation process:
VaR P = {}; For (VAR v In Person. Prototype) {P [v] = person. Prototype [v];} // After the for statement is executed, P already has the showname method. You can cancel the following comments and test the result. // Execution output: // This is showname: undefined in prototype. // P. showname (); // Because the person function contains the followingCode: // This. showname = {} // After this function is executed // The showname variable of Variable P is directed to the new function again. The original direction is nowhere to be found. Person. Call (P ," WWW ", 29 ); // Output: // This is the showname: www In the constructor. P. showname ();