在回调中调用Js `this`上下文

js `this` context in a callback

本文关键字:this 上下文 Js 调用 回调      更新时间:2023-09-26

给定类函数

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上下文如何丢失感到困惑。

在上面的代码中,

  • Works: this.setAll()直接从onResetEvent输出"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(),我到底需要在哪里做绑定?

谢谢

我认为最好从调用者部分传递上下文,它可以使用$.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);
        }
},