手写 call 函数
const myCall = function (context) {
if (typeof this !== "function") return TypeError("not a function");
const ctx = context || window;
const args = [...arguments];
args.splice(0, 1);
ctx.fn = this;
const ret = ctx.fn(...args);
delete ctx.fn;
return ret;
};
const a = 789;
const obj = {
a: 123, b: 456 };
const fn = function () {
console.log(this.a);
};
fn.myCall = myCall;
fn.myCall(obj);
手写 apply 函数
const myApply = function (context) {
if (typeof this !== "function") return TypeError("not a function");
const ctx = context || window;
const args = [...arguments]?.[1];
ctx.fn = this;
let ret = null;
if (Array.isArray(args) && args.length > 0) {
ret = ctx.fn(...args);
} else {
ret = ctx.fn();
}
delete ctx.fn;
return ret;
};
const a = 789;
const obj = {
a: 123, b: 456 };
const fn = function () {
console.log(this.a);
};
fn.myApply = myApply;
fn.myApply(obj);
手写 bind 函数
const myBind = function (context, ...args1) {
if (typeof this !== "function") return TypeError("not a function");
const ctx = context || window;
ctx.fn = this;
return function (...args2) {
const args = [...args1, ...args2];
const ret = ctx.fn(...args);
delete ctx.fn;
return ret;
};
};
function sum(num1, num2) {
console.log(num1, num2, this);
}
sum.myBind = myBind;
const Fn = sum.bind({
name: "bind" }, 1);
Fn(2);
const Fn1 = sum.myBind({
name: "myBind" }, 1);
Fn1(2);