Why do I lose the context of this in Javascript?

后端 未结 3 1094
北荒
北荒 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:51

    If you do it like as follows,

    function will be called in o2 context

    var o2 = {
        a: 11,
        b: 22,
        f2: function (j){
          this.temp = j;
          this.temp();
        }
    };
    

    also these will work too:

    f2: function (j){
          j.apply(this);
    }
    
    f2: function (j){
          j.apply(o2);
    }
    

    Otherwise you call it just like an ordinary function out of context.

    j Is ripped out of its context and you did no tricky closures on it(which is not your intent) so for making "this" work in it you need a scope. The this scope in your question for j is window, which has no "b" in it therefore you get an "undefined".

提交回复
热议问题