在回调中调用Js `this`上下文
js `this` context in a callback
给定类函数
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);
}
},
相关文章:
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- extjs中事件处理程序函数中的THIS上下文
- 在对象文字的声明中继承上下文(this)?“自我”还好吗
- 是否可以绑定javascript函数,使其本地上下文与“this”相同
- 当作为脚本运行时.js Node中“this”的上下文是什么
- 变量“this”上下文在重新赋值变量后未更新
- 浏览器化模块中的“this”上下文
- Node.js:在模块作用域中使用“this”运算符的上下文是什么
- 使用“this”时,函数会丢失上下文 - Raphael JS
- JavaScript承诺:具有绑定的深度嵌套上下文(this)
- d3.js/CoffeeScript:访问mouseover中类和路径的执行上下文(this)
- Angular服务"this"正在更改窗口对象的上下文
- 传递一个原型's函数作为参数而不丢失'this'上下文
- 全局上下文和“this”;在node . js
- ' this '在全局上下文中和内部函数中
- 保留'this'上下文
- 在回调中调用Js `this`上下文
- JS bind(),我需要两个“this”上下文
- 我如何传递一个非'this'上下文到函数
- 调用带有promise和'this'上下文