参考链接:underscore的bindAll和bind到底是什么
underscore中的Functions
Understanding bind and bindAll in Backbone.js
bind的用法
var s = ' Hello';
s.trim(); //输出‘Hello’
var fn = s.trim;
fn();
输出结果:
Uncaught TypeError: String.prototype.trim called on null or undefined
原因:直接调用fn()传入的this指针是undfined
正确用法:
var s = ' Hello';
s.trim(); //输出‘Hello’
var fn = s.trim;
fn.call(s); //输出‘Hello’
或者用bind方法
var s = 'Hello';
s.trim(); //输出‘Hello’
var fn = _.bind(s.trim,s);
fn(); //输出‘Hello’
结论:当用一个变量fn指向一个对象的方法时,直接调用fn()是不行的,因为丢失了this对象的引用。用bind可以修复这个问题。
bindAll的用法
var o = {
para:'hello',
func:function () {
console.log(this.para)
}
};
o.func(); //输出‘Hello’
如果运行如下代码:
var test = o.func();
test(); //TypeError: test is not a function
使用bind函数:
var test = _.bind(o.func,o);
test(); //输出‘Hello’
使用bindAll函数
_.bindAll(o,'func');
var test = o.func;
test(); //输出‘Hello’
//错误用法:var test = _.bindAll(o,'func');test();
看一下官方介绍:
bind
_.bind(function, object, *arguments)
Bind a function to an object, meaning that whenever the function is called, the value of this will be the object. Optionally, pass arguments to the function to pre-fill them, also known as partial application.
「将函数绑定在对象上,不论什么时候调用这个函数,这个函数的this指针都指向该对象」
官方示例:
var func = function(greeting){ return greeting + ': ' + this.name };
func = _.bind(func, {name: 'moe'}, 'hi');
func();
=> 'hi: moe'
bindAll
_.bindAll(object, *methodNames)
Binds a number of methods on the object, specified by methodNames, to be run in the context of that object whenever they are invoked. Very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly useless this. methodNames are required.
官方示例:
var buttonView = {
label : 'underscore',
onClick: function(){ alert('clicked: ' + this.label); },
onHover: function(){ console.log('hovering: ' + this.label); }
};
_.bindAll(buttonView, 'onClick', 'onHover');
// When the button is clicked, this.label will have the correct value.
jQuery('#underscore_button').on('click', buttonView.onClick);
网友评论