0

这是我演示该问题的示例对象。

Dog = Backbone.Model.extend({
    initialize: function () {
    },
    Speak: function (sayThis) {
        console.log(sayThis);
    },
    CallInternalSpeak: function () {
        this.Speak("arf! from internal function.");
    },
    CallSpeakFromClosure: function () {

        this.Speak("arf! fron outside closure.");

        var callClosure = function () {  // think of this closure like calling jquery .ajax and trying to call .Speak in your success: closure
            console.log("we get inside here fine");
            this.Speak("say hi fron inside closure.");  // THIS DOES NOT WORK
        }

        callClosure();
    }
});

var rover = new Dog;

rover.Speak("arf! from externally called function");
rover.CallInternalSpeak();
rover.CallSpeakFromClosure();
4

2 回答 2

1

旧的“自我”技巧......对此进行引用,称其为self,并在函数中引用它。

CallSpeakFromClosure: function () {

    this.Speak("arf! fron outside closure.");
    var self = this;

    var callClosure = function () {  
        console.log("we get inside here fine");
        self.Speak("say hi fron inside closure.");  // THIS DOES NOT WORK
    }

    callClosure();
}
于 2012-04-25T19:51:42.027 回答
1

由于您在 Backbone 中,因此您也可以随时使用 Underscore 的绑定功能。定义 callClosure 后,您可以使用适当的绑定来包装它:

callClosure = _.bind(callClosure, this);
于 2012-04-25T19:57:53.583 回答