javascript - What will alert if you analyze this code?
phpcn_u1582
phpcn_u1582 2017-05-19 10:41:46
0
2
542
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!

phpcn_u1582
phpcn_u1582

reply all (2)
仅有的幸福
json.dbl();//this.val = 2 ⒈ var dbl = json.dbl; ⒉ dbl();//window.val = 2; ⒊ alert(window.val + json.val);//2+2 4

When dbl() is executed, this is the window object, window.val = 2, your fourth part is unnecessary

    世界只因有你
    window.val = 1; var json = { val:10, dbl:function(){ this.val = 2; } }; json.dbl();//这一步,通过json调用dbl方法,把json里面的val值改为2 var dbl = json.dbl;//这步,把dbl函数赋值给dbl dbl();//直接调用dbl函数,函数里面的this指向window,所以把Window.val的值也改为2 json.dbl.call(window);//跟上一句一样,再一次把window.val的值改为2 alert(window.val + json.val);//经过上面的修改,window的val为2,json里面的val为2,所以弹出:2 + 2 = 4
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!