0%

JS 中的 bind 与 call

JS 中调用方法或函数时,有时候需要变更 this 的指向,通常我们会使用 call/apply,而 bind 也可以改变 this 的指向,那么他们有什么区别呢? 简单地说,call/apply 是改变 this 指向时立即调用,而 bind 只是绑定了新的指向,返回的依然是一个 function。举例说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var foo = {
a: 1,
b: 2,
add: function(before, after){
return before + this.a + this.b + after;
}
},
bar = {
a: 3,
b: 4
};
// call
foo.add.call(bar, 'before', 'after'); // #1
// bind
foo.add.bind(bar, 'before', 'after')(); // #2
foo.add.bind(bar)('before', 'after'); // #3

#1,#2,#3 将会返回一样的值。