bind作用:
- 改变this指向,返回一个函数;
- 调用这个方法之后,让this指向传入的第一个参数,并不会直接执行函数只是改变this指向,需要手动调用执行
- call和apply是改变this指向后直接自动执行函数
无参数
Function.prototype.bind1=function(obj){
var that=this;
return function(){
return that.apply(obj);
}
}
function foo(){
console.log(this) ;
}
var obj={"a":123}
foo.bind1(obj)()//{a":123}
有参数
Function.prototype.bind1=function(obj){
var that=this;
var args=[].slice.call(arguments,1);
return function(){
return that.apply(obj,args);
}
}
function foo(){
console.log(this) ;
}
var obj={"a":123}
foo.bind1(obj)()//{a":123}