Start with an interview question: Describe the process of creating an object using the new operator.

In a nutshell, the object creation process is divided into three steps:

1. Create instance object 2. Initialize instance object 3Copy the code

Creating instance Objects

When using the new operator, the operator first creates an empty simple object {}

We then point the constructor of the empty object to the constructor function’s prototype, thus completing the binding of the instance object to the constructor function and assuming that the newly created instance object inherits the constructor function’s prototype

Initializes the instance object

Once you have an instance object, js passes the instance as a reference to this object into the constructor function during execution. Bind this to the instance object of the object to be returned by the constructor function.

Then, inside the constructor, you can add & modify properties and methods to the instance object, completing the value initialization of the instance object

Return instance object

After initialization, a constructor function can return an object, but the content of the object returned depends on whether a reference type is returned inside the function

1, if returned to the reference type data, then will directly to the constructor function value (object/function) cover initialize an instance of the object to be completed before, and will return to the instance of the object this value as the final 2, if the return value type of data (such as true, 'ABC', 1), etc., so the constructor function will ignore the return value, 3. If no value is returned, the constructor function returns the initialized instance directlyCopy the code