This is a special keyword in JS that is automatically saved in the scope of all functions.
Why do you use this
This provides an object way to implicitly pass a reference to an object, so the API design can be simple and easy to reuse. Look at the comparison of the following two sections of code:
functionIdentify () {return This. Name; } functionspeak () {return"Hello,i AM" + identify.call ( This); } varme ={name:"Tony" }; varyou ={name:"Walker" }; varMan =Identify.call (you); Console.log (man); //Walker varBoy =Speak.call (Me); Console.log (boy); //Tony
This Code
function Identify (context) { return context.name; } function Speak (context) { return "Hello i am" + identify (context); } var me = { name:"Tony" }; var you = { name:"Walker" }; Console.log (Identify (Me)); Console.log (speak (you));
Context CodeThis misunderstanding
1.this points to the function itself. The following code lets you see that this does not point to the function itself as I think.
function foo (i) { console.log ("foo:" + i); this. count++; } = 0; for (var i =0;i<10;i++) { if(i>5) { foo (i); } }; // 0
JS functions as an object, you can store the state (the value of the property) when the function is called, execute Foo.count = 0 o'clock, and do want the function to add a property count. However, this in the function internal code this.count does not point to the function object.
2.this refers to the scope of the function. It is important to be clear that this is a lexical scope that does not point to the function in any case.
function Boo () { var a = 0; This . Bar (); } function Bar () { Console.log (this//A is undefined }
What exactly is this?
This is bound at run time and is not bound at the time of writing, its context depends on the various conditions when the function is called. The This binding and the function declaration have no relation, only depending on how the function is called. When a function is called, an activity record is created that contains the function where it is called (the call stack), the invocation method, the method of communication, and so on. It can be said who called this to point to WHO.
This is actually a binding that occurs at the time of the function call, and what it points to exactly depends on where the function is called.
The next article will explain this in detail.
About the This--javascript in