To create Person New instance of , Must use new Operator . Calling a constructor in this way actually goes through the following 4
Steps :
(1) Create a new object ;
(2) Assign the scope of the constructor to the new object ( therefore this It points to this new object ) ;
(3) Execute code in constructor ( Add properties for this new object ) ;
(4) Return to new object .

 

new Operator

After the introduction of the above basic concepts , Add new Operator , We can complete the traditional object-oriented class + new Create objects in , stay JavaScript
<http://lib.csdn.net/base/javascript> in , We've made this kind of approach Pseudoclassical.
Based on the above example , We execute the following code

 

  var obj = new Base();  
What is the result of this code , We are Javascript The object model seen in the engine is :


new What do operators do ? It's very simple , I did three things .

 

  var obj  = {}; obj.__proto__ = Base.prototype; Base.call(obj);  
first line , We created an empty object obj
Second line , We put the __proto__ Members point to Base Function object prototype member object

The third line , We will Base Function object's this Replace pointer with obj, Then call Base function , So we give it obj Object assigned a id Member variable , The value of this member variable is ”base”, about call Function usage .

 


If we give Base.prototype What's the effect of adding some functions to ?
For example, the code is as follows :

 

  Base.prototype.toString = function() {     return this.id; }  
So when we use new When creating a new object , according to __proto__ Characteristics of ,toString This method can also be used to create new objects . So we saw :

Structural subunits , Let's set it up ‘ class ’ Member variables for ( for example : In the example id), Construct subobject prototype Let's set ‘ class ’ Public method of . So through the function object and Javascript Unique __proto__ And prototype Members and new Operator , Simulate the effect of class and class instantiation .