call
Function.prototype.call(this, arg1, arg2, …..)
能够转变this,而且传入参数,马上实行,返回函数返回值
手写call
Function.prototype.myCall = function(context = window, ...args) {
context = context || window; // 参数默认值并不会消除null,所以从新赋值
context.fn = this; // this是挪用call的函数
const result = context.fn(...args);
delete context.fn; // 实行后删除新增属性
return result;
}
apply
Function.prototype.apply(this, [arg1, arg2, …..])
能够转变this,而且传入参数,与call差别的是,传入的参数是数组或类数组,马上实行,返回函数返回值
手写apply:
Function.prototype.myApply = function(context = window, args = []) {
context = context || window; // 参数默认值并不会消除null,所以从新赋值
context.fn = this; // this是挪用call的函数
const result = context.fn(...args);
delete context.fn;
return result;
}
bind
Function.prototype.bind(this, arg1, arg2, …)
能够绑定this,而且传入参数,体式格局与call雷同,然则不会实行,返回已绑定this的新函数
手写bind:
Function.prototype.myBind = function(context, ...args) {
const _this = this;
return function Bind(...newArgs) {
// 斟酌是不是此函数被继续
if (this instanceof Bind) {
return _this.myApply(this, [...args, ...newArgs])
}
return _this.myApply(context, [...args, ...newArgs])
}
}