0

我是 Backbone、Javascript、jQuery 菜鸟,并试图解决问题。在我的 Backbone 视图中,我有这个方法:

    setError: function (selection, text) {
        console.log("set error");
        this.$el.find(selection).html(text);
        this.$el.find(selection).show();
    },

我想从填充错误字段的另一个方法调用此方法,并在 div 中附加其他消息。所以我尝试像这样调用 setError :

     populateErrors: function (sampleErrors) {
       console.log("populateErrors");
        _.each(sampleErrors, function (sample) {
            // Set the error
            this.setError('#sample-error', 'test');
            $('#sample-validation-form').append('<p>testing</p>');
        }, this);
    }

我不明白的是如何调用 setError。因此,如果我在 _.each 语句之外调用它,我可以执行 this.setError。这对我来说很有意义,因为我用这个 Backbone 对象调用 setError。至少我是这么解释的。请让我知道这是否不正确。

但是在 _.each 语句中,我想既然我将语句与this作为最后一个参数绑定,我认为我不需要this在 setError 前面。但是当我尝试这样做时,我得到 setError 是未定义的。所以然后我尝试如上所示,但是当我在 _.each 循环之外this.setError调用时,我没有得到我的“测试”输出。this.setError有人可以向我解释一下这个函数上下文在这个例子中是如何工作的。我彻底糊涂了!提前致谢!

4

2 回答 2

1

当您将对象foo作为第三个参数传递时,您是在说:在匿名函数中,this应该是foo.

populateErrors: function (sampleErrors) {
    // `this` is the Backbone view here
    this.setError('#sample-error', 'test');

    _.each(sampleErrors, function (sample) {
        // since you passed the view (this) to `each`
        // `this` is the Backbone view here also
        this.setError('#sample-error', 'test');
    }, this);
}
于 2013-04-01T15:32:11.450 回答
0

_.each 的第三个参数是上下文。javascript 函数的上下文是对函数中“this”的引用。通过传递“this”,您可以保留当前上下文。

例如:

populateErrors: function (sampleErrors) {
   var x = {
          blah: "x context"
       };

   this.blah = "orig context";

   console.log("populateErrors");

    _.each(sampleErrors, function (sample) {
        // Here, your current context is the same context as 
        // when you called populate Errors
        // this.blah === "orig context";
    }, this);

    _.each(sampleErrors, function (sample) {
        // Here, you've defined a different context.
        // this.blah === "x context";
    }, x);
}

唯一一次可以避免使用“this”。在你的表达前面是当你使用“with”关键词时。请参阅https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/with

于 2013-04-01T16:13:02.807 回答