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

バックボーンを使用しているため、いつでもアンダースコアのバインド機能を使用できます。callClosureを定義したら、適切なバインディングでラップできます。

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

古い「自己」トリック...これを参照し、それを自己と呼び、関数で参照します。

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 に答える