我最近开始在游戏中使用 backbone.js。我使用模型创建定时器如下:
var Timer = Backbone.Model.extend({
defaults: {
'hh':00, 'mm':05, 'ss':00
},
initialize: function() {
},
countDownOnce: function() {
// Count down the time by 1 sec
},
run1: function() {
this.countDownOnce();
}
run2: function() {
setInterval(this.countDownOnce, 1000);
}
});
countDownOnce 函数,如果像在 run1 中那样直接调用,工作正常。
但如果该函数作为参数传递给某个内置函数,例如 run2 函数中的 setInterval,this 的值将丢失。
如何将this指针传递给内置函数?
最佳答案
Backbone 文档有一个关于 binding "this" 的有用部分.
基本上,Underscore提供了几个非常有用的功能,_.bind and _.bindAll ,这有助于您更轻松地管理“this's context”。
...
initialize: function() {
_.bindAll(this, 'countDownOnce' //, and whatever other functions you want bound)
}),
...
这将确保无论从什么上下文中调用它,countDownOnce 中的“this”都指向您的 Timer 实例。
关于this - *this* 在 Backbone.js 的嵌套函数调用中的传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6965616/