【发布时间】: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(),我究竟需要在哪里进行绑定?
谢谢
【问题讨论】:
-
你在两个月前问过nearly the same question。
标签: javascript jquery callback this