New
- Create a new object;
- Assigns the scope of the constructor to the new object (so this points to the new object);
- Executes the code in the constructor (adding attributes to the new object);
- return new Object
Describe the words in code (forget Proyotype, apply, etc. ):
1 function New (f) {2 var n = {' __proto__ ': F.prototype};/* First step */3 return function () {4 f.apply (n, arguments); /* Second step */5 return n; };7}
This
This is a pointer that always points to the new object instance of the nearest parent
When the page loads, the JavaScript engine completes the Windows instantiation, and this point points to Windows;
1 console.log (this = = = window); // 2 var value = "I ' M proproty of window Instance " 3 console.log (value = = = Window.value); // 4 function Show () { this = = = window); // 6 7 Show ();
This in the object will only point to the new object when new object is newly.
Note :var obj = {} is also new
1 var show = {2do function() {3 Console.log ( this); // obj 4 Console.log ( this = = = window); // false 5 } 6}7 show. Do ();
Special attention is paid to the following situations:
1 varShow = {2 Do:function(){3Console.log ( This);//window4Console.log ( This= = = window);//false5 }6 }7 8 var dofun = Show. Do ;9Dofun ();
Show.do (): Do function as a show object is called. So, the context refers to show;
Dofun (): Show.do is assigned to the Dofun variable because Dofun is implicitly set as a property of the global object, so the context of Dofun refers to the window
Call & Apply
Grammar:
Call ([thisobj[,arg1[, arg2[, [,. ArgN]]])
Apply ([Thisobj[,argarray]])
Call and apply are changes to the scope of the function (scope/context);
Assigns the scope of the constructor to the new object (see new Second, at which point this is pointed at);
Call and apply are the first parameters that point this to the method.
1 varValue = "I ' m proproty of Window instance";2 functionShow () {3Console.log ( This);4Console.log ( This. value);5 }6 7 varobj = {8Value: "I ' m proproty of obj instance"9 };Ten One /* A * Window - * i ' m proproty of window instance - */ the Show (); - - /* - * obj + * i ' m proproty of obj instance - */ +Show.call (obj);
JavaScript starts with object new and simply understands this/call/apply.