求大神解释下js
中的bind
的用法,他和call
和apply
都有哪些区别
bind
是固定某个函数的参数和this
,返回另外一个函数。call
和 apply
是指定this和参数调用这个函数,立即执行这个函数。call
apply
的区别是他们指定参数的方式不同。
比如
function fn(a,b){
console.log(this);
console.log(a);
console.log(b);
}
// bind(this,args...)
bf = fn.bind("Bind this",10); // 没有任何输出,也就是说没有执行这个函数
bf(); // "Bind this",10,undefined
bf(20);// “Bind this”,10,20
// 原函数不受影响
fn(1,2); //window, 1,2
bf2 = fn.bind("Bind this",1,2);
bf2(); // "Bind this",1,2
// call(this,args...)
fn.call("Call this",1) // "Call this",1,undefined
fn.call("Call this",1,2) // "Call this",1,2
// apply(this,[args])
fn.apply("Apply this",[1]) // "Apply this",1,undefined
fn.apply("Apply this",[1,2]) // "Apply this",1,2
先来个总结
apply 、 call 、bind 三者都是用来改变函数的this对象的指向的;
apply 、 call 、bind 三者第一个参数都是this要指向的对象,也就是想指定的上下文;
apply 、 call 、bind 三者都可以利用后续参数传参;
bind是返回对应函数,便于稍后调用;apply 、call 则是立即调用 。
绑定bind的ES3实现
if(!Function.prototype.bind){
Function.prototype.bind = function(o, args){
var self = this,
boundArgs = arguments;
return function(){ //此时返回的只是一个函数
var args = [], i;
for(var i=1; i< boundArgs.length; i++){
args.push(boundArgs[i]);
}
for(var i =0; i< arguments.length; i++){
args.push(arguments[i]);
}
return self.apply(o, args);
}
}
}
var sum = function(x,y){ return x+y };
var result = sum.bind(null,1);
result(2); // 3