Why do I lose the context of this in Javascript?

后端 未结 3 1083
北荒
北荒 2020-12-10 14:20

I have this simple code :

var o = {
    a: 1,
    b: 2,
    f1: function ()
    {
        alert(this.b);
    }
}

var o2 = {
    a: 11,
    b: 22,
    f2: f         


        
3条回答
  •  不思量自难忘°
    2020-12-10 14:49

    Check this tests:

    o.f1(); // alerts 2
    
    var f3 = o.f1; // (*)
    
    f3(); // alerts undefined
    
    o2.f2(f3); // alerts undefined
    
    f3.apply(o2); // alerts 22
    

    I realize that when you pass a function as parameter the context is lost exactly the same way it's lost in the (*) pointed in the code above.

    What happening is j = arguments[0] = o.f1 and at this point you lose the context.

    When passes a function as a parameter you are just passing the reference in memory to that function. Without bind the context you'll fail the simple j() call. That's why you need to use apply or the this trick showed by Ihsan.

提交回复
热议问题