Explanation of the new operator in JavaScript advanced programming:
New operator causes the constructor to change as follows:
1. Create a new object;
2. Assign the scope of the constructor to the new object (so this one points to the new object);
3. Execute the code in the constructor (add attributes for this new object);
4. returning new objects
/*Constr: Constructor args: Initialize parameters*/functionnewoperator (constr, args) {varThisvalue = Object.create (Constr.prototype);//Create a new object with the constructor's prototype object varresult = Constr.apply (Thisvalue, args);//point the constructor to the new object and add a new property to the new function if(typeofresult = = = ' object ' && result!==NULL) { returnResult//return new Object } returnThisvalue;}
Look at the results of this piece of code
var a=5; function Test () { a=0; alert (a); Alert (this. a); var A; alert (a);} Test (); New test (); 0500undefined0
And look at the results of this code.
var a=5; function Test () { this.a=0; alert (a); Alert (this. a); var A; alert (a);} Test (); New test (); undefined0undefinedundefined0undefined
This code can be interpreted as defining var A; Then a is the local variable of the function, which can only be found within his active object, and when the test () is executed, THIS.A is equivalent to WINDOW.A, and when the new test () is executed, THIS.A This is equivalent to the property of the new object, and a is a local variable of the test function, which is okay with the new object
The study of new constructor in JS