call,apply,bind函数其本质是实现改变函数上下文环境,即改变this
call实现
Function.prototype._call = function (context) {
var context = context || window;
context._fn_ = this;
var [_this, ...args] = arguments
var result = context._fn_(...args)
delete context._fn_;
return result;
}
复制代码
apply实现
Function.prototype._apply = function (context) {
var context = context || window;
context._fn_ = this;
var [_this, args] = arguments
console.log('args :', args);
var result = context._fn_(...args)
delete context._fn_;
return result;
}
复制代码
bind实现
借助apply实现
Function.prototype._bind = function (context, ...args) {
return () => {
this.apply((context || window), args)
}
}
复制代码
纯原生实现
Function.prototype._bind2 = function (context=window, ...args) {
context._fn_ = this
return () => {
context._fn_(...args);
}
}
复制代码