To create Person New examples, Must use new Operator. Calling a constructor in this way actually goes through the following 4
One step:
(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, Plusnew Operator, We can complete the traditional object-orientedclass + new Create objects in, stayJavaScript
<> in, We've made this kind of approachPseudoclassical.
Based on the above example, We execute the following code


  var obj = new Base();  
What is the result of this code, We areJavascript 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;;  
first line, We created an empty objectobj
Second elements, We put the__proto__ Members point toBase Function objectprototype member object

Third elements, We willBase Function object'sthis Replace pointer withobj, Then callBase function, So we give itobj Object assigned aid Member variables, The value of this member variable is”base”, aboutcall Function usage.


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


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

Constructor, Let's set it up‘ class’ Member variables for( for example: Examples ofid), Construct subobjectprototype Let's set‘ class’ Public method of. So through the function object andJavascript Peculiar__proto__ Andprototype Members andnew Operator, Simulate the effect of class and class instantiation.