search

Home  >  Q&A  >  body text

javascript - What will alert if you analyze this code?

    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_u1582phpcn_u15822775 days ago588

reply all(2)I'll reply

  • 仅有的幸福

    仅有的幸福2017-05-19 10:43:46

    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

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-19 10:43:46

    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

    reply
    0
  • Cancelreply