javascript - 为什么不使用 _.bind 而不是 _.bindAll?

标签 javascript backbone.js underscore.js

在此 Backbone 示例中:

http://arturadib.com/hello-backbonejs/docs/1.html

(function($){
  var ListView = Backbone.View.extend({
    el: $('body'), // attaches `this.el` to an existing element.
    initialize: function(){
      _.bindAll(this, 'render'); // fixes loss of context for 'this' within methods
      this.render(); // not all views are self-rendering. This one is.
    },
    render: function(){
      $(this.el).append("<ul> <li>hello world</li> </ul>");
    }
  });
  var listView = new ListView();
})(jQuery);

因为只传递了一个参数(函数),所以我看不出使用bindAll()有什么意义。

这是underscore API

最佳答案

_.bindAll 将对象中的方法替换为新方法,并将上下文设置为该对象。 _.bind 返回一个新函数。

这相当于:

this.render = _.bind(this.render, this)

这有点冗长,但无论如何都在 underscore 内完成。 :

_.bindAll = function(obj) {
    var funcs = slice.call(arguments, 1);
    if (funcs.length === 0) throw new Error('bindAll must be passed function names');
    each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); //in this line
    return obj;
  };

关于javascript - 为什么不使用 _.bind 而不是 _.bindAll?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24591316/

相关文章:

Javascript表格行显示/隐藏

jquery - 主干网和jqm : back button how to restore page context

javascript - 从我的数据数组中获取 [object Object]

javascript - 奇怪的 Chrome 开发者工具调试器错误

javascript - 在 lodash.js 中,它会缓存 `.value()` 方法的结果吗?

javascript - 同一个函数参数可以接受不同的数据类型吗?

javascript - Telegram bot api - answerInlineQuery 中的 QUERY_ID_INVALID - Javascript

javascript - Node JS 在类 B 中实例化类 A

javascript - JavaScript 中的原型(prototype)继承约定

javascript - 使用纯 JavaScript 交错附加元素