When writing JavaScript, we often encounter the concept of this. The point of this is always a headache. Today, I will summarize this in one sentence based on my understanding of this and some experience. So this sentence is:
This directs to the caller when there is a function caller. Otherwise, it points to global, except for Call and apply.
Let's use an example to understand and remember this sentence:
1 Function Test (){ 2 Console. Log ( This ); 3 } 4 Test (); // Window 5 VaR Th = {}; 6 Test. Call (th) // Th 7 Test. Apply (th) // Th 8 VaR A = Function (){ 9 } 10 A. test = Test; 11 A. Test (); // Function 12 A. Prototype = { 13 Test: Test 14 } 15 VaR B = New A (); 16 B. Test (); // B; 17 A. Prototype. Test () // A. Prototype 18 SetTimeout (B. Test, 100) // Window 19 Document. Body. onclick = Function (E ){ 20 B. Test (); // B 21 Test (); // Window 22 Console. Log ( This ) // Document. Body 23 } 24 Function Callmethod (callback ){ 25 Callback (); // Window 26 Arguments [0] ();// Arguments --> arguments.0 () 27 } 28 Callmethod (B. test );
In the above example, the Comment position shows the current point of this. We can see that this can be an object or a function, and point to the caller when there is a caller, call and apply can change this in the function. Other times point to global (window in the browser ). As is exactly the same as Js.
Next let's talk about the point of this when calling Javascript and:
When JS calls the as function, this inside the as function points to root.
What happens when the as calls JS? In fact, we still follow the above sentence. See the following example.
1 /// as Code 2 externalinterface. call ("test" ); 3 externalinterface. call ("test. test "); 4 // JS Code 5 function test () { 6 console. log ( This ); 7 } 8 test. test = test;
In the as code, if the global function test is called and no caller is specified, this in the test function points to global and the second sentence of AS is called, is to call test under test, so this will point to the function test, that is, as calls JS, the point of this is not related to, the method for determining this is exactly the same as that used in JS internal calls.
Remember this in one sentence, right ~ Xi ~