Passing around function including its context in javascript

后端 未结 3 957
遥遥无期
遥遥无期 2021-01-21 01:36

There is something I don\'t understand in javascript and broke down a sample problem to an essential case:

    a = function () {
      this.b = 5;
    }

    a.p         


        
3条回答
  •  广开言路
    2021-01-21 02:07

    You need to call the method using the object to get the context right. So:

    var e = function() { return d.c(); };
    

    In newer browsers you can use the bind method to do the same:

    var e = d.c.bind(d);
    

    In jQuery for example there is the proxy method that you can use also in older browsers:

    var e = $.proxy(d.c, d);
    

提交回复
热议问题