需要解释Underscore.js中的_.bindAll()函数

Nik*_* So 83 javascript backbone.js underscore.js

我一直在学习一些backbone.js,并且我已经看到了很多_.bindAll()使用过的实例.我已经阅读了整个backbone.js和underscore.js文档页面,试图了解它的作用,但我仍然非常模糊它的作用.这是下划线的解释:

_.bindAll(object, [*methodNames]) 
Run Code Online (Sandbox Code Playgroud)

在methodNames指定的对象上绑定许多方法,以便在调用它们时在该对象的上下文中运行.非常方便用于将用作事件处理程序的绑定函数,否则将使用相当无用的调用.如果没有提供methodNames,则所有对象的函数属性都将绑定到它.

var buttonView = {
  label   : 'underscore',
  onClick : function(){ alert('clicked: ' + this.label); },
  onHover : function(){ console.log('hovering: ' + this.label); }
};

_.bindAll(buttonView);

jQuery('#underscore_button').bind('click', buttonView.onClick);
=> When the button is clicked, this.label will have the correct value...
Run Code Online (Sandbox Code Playgroud)

如果你可以通过给出另一个例子或者一些口头解释来帮助这里,任何事情都会受到赞赏.我试图搜索更多的教程或示例,但是nil就是我需要的东西.大多数人似乎只知道自动做什么......

Thi*_*ter 65

var Cow = function(name) {
    this.name = name;
}
Cow.prototype.moo = function() {
    document.getElementById('output').innerHTML += this.name + ' moos' + '<br>';
}

var cow1 = new Cow('alice');
var cow2 = new Cow('bob');

cow1.moo(); // alice moos
cow2.moo(); // bob moos

var func = cow1.moo;
func(); // not what you expect since the function is called with this===window
_.bindAll(cow1, 'moo');
func = cow1.moo;
func(); // alice moos
Run Code Online (Sandbox Code Playgroud)
<div id="output" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
Run Code Online (Sandbox Code Playgroud)

不幸的是,实际的"绑定所有"功能仅适用于对象上的函数.要包含在原型上定义的函数,您需要明确地将这些函数名称作为附加参数传递给_.bindAll().

无论如何,你想要一个解释:基本上它允许你用一个具有相同名称和行为的函数替换对象上的函数,但也绑定到该对象,所以this === theObject即使不将其作为方法(theObject.method())调用.

  • [Yehuda Katz撰写的这篇博文](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/)很好地解释了JavaScript中的`this`. (9认同)

Rom*_*din 9

对我来说最简单的解释是下一个:

initialize:function () { //backbone initialize function
    this.model.on("change",this.render); //doesn't work because of the wrong context - in such a way we are searching for a render method in the window object  
    this.model.on("change",this.render,this); //works fine
    //or 
    _.bindAll(this,'render');
    this.model.on("change",this.render); //now works fine
    //after  _.bindAll we can use short callback names in model event bindings
}
Run Code Online (Sandbox Code Playgroud)