JavaScript 'this' 关键字

标签 javascript underscore.js this

var PlaylistView = Backbone.View.extend({
  el: '#expanded-container',

  initialize: function() {
    this.bg = chrome.extension.getBackgroundPage();
    this.$('.list-group').empty();
    var realThis = this;
    _.each(this.bg.Playlist.models, function (song) {
      // append to playlist, rendering song template?
      var songView = new SongView({ model: song });
      console.log(realThis); // THIS is what I want
      console.log(this) // this is NOT what I want
      //this.$el.append(songView.render().el); // hence, this does NOT work
      realThis.$el.append(songView.render().el); // and THIS works
    });
  }
});

在上面的代码中,_.each()函数中的this指向全局window对象,因为_.each () 由窗口调用。但是,我仍然希望 this 指向 PlaylistView。我遇到过很多类似的情况,我经常定义一个变量来存储 this 的初始值,就像提供的示例中的 realThis 变量一样。还有其他常规方法可以解决这个问题吗?

注意:我正在关注 this学习Backbone的书,它显示了以下代码作为示例。

var ListView = Backbone.View.extend({
  render: function(){

    // Assume our model exposes the items we will
    // display in our list
    var items = this.model.get('items');

    // Loop through each of our items using the Underscore
    // _.each iterator
    _.each(items, function(item){

      // Create a new instance of the ItemView, passing 
      // it a specific model item
      var itemView = new ItemView({ model: item });
      // The itemView's DOM element is appended after it
      // has been rendered. Here, the 'return this' is helpful
      // as the itemView renders its model. Later, we ask for 
      // its output ("el")
      this.$el.append( itemView.render().el ); // <--- *THIS IS WRONG?
    }, this);
  }
});

在这种情况下,_.each 循环中的 this 是否会指向错误的对象,就像在我的代码中一样?这是书上的错误还是我误解了什么?谢谢!

引用:Learning this keyword

最佳答案

来自http://underscorejs.org/#each :

each _.each(list, iterator, [context])

The iterator is bound to the context object, if one is passed.

initialize()中,this指向您的Backbone View。如果您将 this 作为第三个参数传递给 _.each(),那么 this 将在迭代器函数中引用您的 Backbone View。

I have faced many similar situations and I often defined a variable that stored the initial value of this, just like realThis variable in the provided example. Is there any other conventional way to deal with this?

是的。如果您处于 ES5(非 IE8)环境中,请使用 Function.prototype.bind() 。为了向后兼容,请使用 _.bind() .

var func = function (greeting) {
  return greeting + ': ' + this.name;
};

if (usingUnderscore) {
  func = _.bind(func, {name: 'moe'}, 'hi');
} else if (es5environmentHooray) {
  func = func.bind({name: 'moe'}, 'hi');
}

func();
=> 'hi: moe'

关于JavaScript 'this' 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23123069/

相关文章:

javascript - 给定一个 JSON 格式的数据框,我如何自动为 D3 中的变量分配颜色?

JavaScript 排序

javascript - 尝试理解 Node js 服务器概念

javascript - 如何使用 Backbone.Paginator.js 运行多个实例?

javascript - 对 JavaScript 集合中的对象进行排序

javascript - 如何使用 JavaScript/XUL 向新的浏览器选项卡发出发布请求?

javascript - 使用下划线模板构建数独板

javascript - jquery在ajax中调用函数时this指针作用域

以对象作为参数的 JavaScript 函数

javascript - 这。引用对象而不是窗口对象