window.val = 1; var json = { val:10, dbl:function(){ this.val = 2; } }; json.dbl();//this.val = 2 ⒈ var dbl = json.dbl; ⒉ dbl();//window.val = 1; ⒊ json.dbl.call(window);//this指向变为window,并且执行,window.val = 1; ⒋ alert(window.val + json.val);//json指向为window,所以val为1,1+1=2??? ⒌
The comments were my initial understanding, and then after seeing the results, I tried to use the answers to think backwards to find the reasons.
==========================The dividing line after reading the answer============== ============
After step 2, this is still dbl, and val is 2 at this time. After step 2, window.val = 1 is directly called, and then the call changes the point of this and executes it. This points to window and directly overwrites the val attribute under window, so window.val is 2, and the last step 2 becomes 2 2 = 4.
I don’t know if this idea is correct, please give me some advice, thank you!
When dbl() is executed, this is the window object, window.val = 2, your fourth part is unnecessary