this - *this* 在 Backbone.js 的嵌套函数调用中的传播

标签 this backbone.js

我最近开始在游戏中使用 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/

相关文章:

java - 使用 "this.xxx"指向字段时有性能差异吗?

javascript - 如果模型包含使用 findWhere 存在的键,则返回 Backbone 模型

javascript - 使用 JavaScript "this"更改文本框中的文本?

javascript - 在 javascript 中链接回调并保留 'this'

c++ - noexcept 规范中是否允许使用 `this`?

javascript - 当我在主干中的另一个地方调用相同的函数时如何传递 e.target 值

javascript - requirejs - 从全局空间获取问题

php - Backbone.js 如何与 PHP 一起使用

json - 从 json 文件填充集合

JavaScript - 我可以获得方法的父对象吗?