Function.prototype.myApply = function (context) {
if (context === undefined || context === null) {
context = globalThis;
} else {
context = Object(context);
}
let fn = Symbol("myFn");
context[fn] = this;
let result;
let arg = arguments[1];
if (!Array.isArray(arg)) {
result = context[fn]();
} else {
let _arg = Array.from(arg);
result = context[fn](..._arg);
}
delete context[fn];
return result;
};
Function.prototype.myCall = function (context) {
if (context === undefined || context === null) {
context = globalThis;
} else {
context = Object(context);
}
let fn = Symbol("myFn");
context[fn] = this;
let result;
if (arguments.length > 1) {
let arg = Array.from(arguments).slice(1);
context[fn](...arg);
} else {
context[fn]();
}
delete context[fn];
return result;
};
//apply实现bind
Function.prototype.myBind = function (context, ...arg) {
let fn = this;
let args = arguments;
return function (...callArgs) {
return fn.apply(context, args.length > 1 ? arg.concat(callArgs) : null);
};
};
//call实现bind
Function.prototype.myBind2 = function (context, ...arg) {
let fn = this;
let args = arguments;
return function (...callArgs) {
let _args = args.length > 1 ? [...arg, ...callArgs] : callArgs;
return fn.call(context, ..._args);
};
};
const person = {
name: "Alice",
greet: function () {
console.log(`Hello, ${this.name}!`);
},
};
const anotherPerson = {
name: "Bob Apply",
};
const anotherCallPerson = {
name: "Bob Call",
};
const anotherBindPerson = {
name: "Bob Bind",
};
// 使用 apply 方法改变 greet 函数执行时的上下文为 anotherPerson
person.greet.myApply(anotherPerson); // 输出:Bob Apply
person.greet.myCall(anotherCallPerson); // 输出:Bob Call
person.greet.myBind(anotherBindPerson)(); // 输出:Bob Bind
手写apply,call,bind
于 2024-05-11 17:27:28 首次发布