注:本文只是简单实现,表达核心原理,边界情况不予考虑
call
javascript
Function.prototype.myCall = function (thisBinds, ...args) {
// 判空,默认为 window
thisBinds = thisBinds ? Object(thisBinds) : window;
// 在目标上保存需要绑定的函数
thisBinds.fn = this;
// 用目标去调用要绑定的函数,函数的 this 会指向目标
const result = thisBinds.fn(...args);
// 删除目标上的函数
delete thisBinds.fn;
// 返回执行后的结果
return result;
};
Function.prototype.myCall = function (thisBinds, ...args) {
// 判空,默认为 window
thisBinds = thisBinds ? Object(thisBinds) : window;
// 在目标上保存需要绑定的函数
thisBinds.fn = this;
// 用目标去调用要绑定的函数,函数的 this 会指向目标
const result = thisBinds.fn(...args);
// 删除目标上的函数
delete thisBinds.fn;
// 返回执行后的结果
return result;
};
apply
javascript
Function.prototype.myApply = function (thisBinds, args) {
// 判空,默认为 window
thisBinds = thisBinds ? Object(thisBinds) : window;
// 在目标上保存需要绑定的函数
thisBinds.fn = this;
let result;
// 由于参数是数组,所以需要判断是否有传参数
if (!args) {
// 用目标去调用要绑定的函数,函数的 this 会指向目标
result = thisBinds.fn();
} else {
// 用目标去调用要绑定的函数,函数的 this 会指向目标
result = thisBinds.fn(...args);
}
// 删除目标上的函数
delete thisBinds.fn;
// 返回执行后的结果
return result;
};
Function.prototype.myApply = function (thisBinds, args) {
// 判空,默认为 window
thisBinds = thisBinds ? Object(thisBinds) : window;
// 在目标上保存需要绑定的函数
thisBinds.fn = this;
let result;
// 由于参数是数组,所以需要判断是否有传参数
if (!args) {
// 用目标去调用要绑定的函数,函数的 this 会指向目标
result = thisBinds.fn();
} else {
// 用目标去调用要绑定的函数,函数的 this 会指向目标
result = thisBinds.fn(...args);
}
// 删除目标上的函数
delete thisBinds.fn;
// 返回执行后的结果
return result;
};
bind
javascript
Function.prototype.myBind = function (thisBinds, ...bindArgs) {
// 判空,默认为 window
thisBinds = thisBinds ? Object(thisBinds) : window;
// 在目标上保存需要绑定的函数
thisBinds.fn = this;
// 因为 bind 是需要延迟执行的,所以这里采用闭包
return function (...newArgs) {
// 合并 bind 传参和新函数的传参
const args = [...bindArgs, ...newArgs];
// 用目标去调用要绑定的函数,函数的 this 会指向目标
const result = thisBinds.fn(...args);
// 删除目标上的函数
delete thisBinds.fn;
// 返回执行后的结果
return result;
};
};
Function.prototype.myBind = function (thisBinds, ...bindArgs) {
// 判空,默认为 window
thisBinds = thisBinds ? Object(thisBinds) : window;
// 在目标上保存需要绑定的函数
thisBinds.fn = this;
// 因为 bind 是需要延迟执行的,所以这里采用闭包
return function (...newArgs) {
// 合并 bind 传参和新函数的传参
const args = [...bindArgs, ...newArgs];
// 用目标去调用要绑定的函数,函数的 this 会指向目标
const result = thisBinds.fn(...args);
// 删除目标上的函数
delete thisBinds.fn;
// 返回执行后的结果
return result;
};
};