bind, apply, call 的实现与区别
三者均用于显示绑定 this.
区别:
- bind 返回的是一个函数;
- apply 的第二个参数是数组形式;call 的参数是 (this, arg1, arg2…)
实现:
function myCall( context){
var context = context || window;
var args = arguments.slice(1);
context.func = this;
var result = context.func( ...args);
delete context.func;
return result;
}
function myApply( context){
var context = context || window;
context.func = this;
var result;
if( arguments.length === 1){
result = context.func();
}
else{
var args = arguments.slice(1);
result = context.func( args);
}
delete context.fun;
return result;
}
function myBind( context){
var _this = this;
var args = arguments.slice(1);
return function( ){
return _this.apply(context, args);
}
}