【问题标题】:js `this` context in a callback [duplicate]回调中的js`this`上下文[重复]
【发布时间】:2014-05-20 23:56:28
【问题描述】:

给定类函数

game.PlayScreen = me.ScreenObject.extend({  

    onResetEvent: function() {
        this.setAll(); //calls setAll(), which calls setGlobals()
        this.saveNextLevelData(this.setAll);
    },

    saveNextLevelData : function (callback) {
        $.get("./php/CRUD.php", {},
            function (returned_data) {
                callback(); //however, the callback of setAll throws 
                           `undefined is not a function` error
            }
    },

    setAll : function () {
         log("setAll called");
         this.setGlobals();
    },

    setGlobals : function () {
         log("setGlobals called");
    }
});

基本上,我对调用回调函数时this 上下文如何丢失感到困惑。

在上面的代码中,

  • 工作:直接从onResetEvent调用this.setAll()输出"setAll called""setGlobals called"

  • 中断callback()$.get调用this.setAll()输出"setAll called"this.setGlobals();中断...我认为由于丢失this上下文...它输出Uncaught TypeError: undefined is not a function

当您调用包含属于父对象(在本例中为this)的函数的回调函数时,我试图遵循this 的上下文。如果我想从this.setAll() 的回调中调用this.setGlobals(),我究竟需要在哪里进行绑定?

谢谢

【问题讨论】:

标签: javascript jquery callback this


【解决方案1】:

我认为最好从调用者部分传递上下文,可以使用$.proxy()/Function.bind()所以

this.saveNextLevelData($.proxy(this.setAll, this));

另一个解决方案是将当前对象作为上下文从 ajax 回调传递给回调,问题是默认情况下回调中的this 将引用 ajax 设置对象。所以

saveNextLevelData : function (callback) {
    var self = this;
    $.get("./php/CRUD.php", {},
        function (returned_data) {
            callback.call(self);
        }
},

【讨论】:

  • $.proxy() 返回一个函数引用,它将调用作为第一个参数传递的函数,并将上下文作为作为第二个参数传递的对象
  • @Growler:也许你应该阅读他为你提供的文档。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-13
  • 2012-12-27
  • 2021-10-16
  • 1970-01-01
相关资源
最近更新 更多