手写 bind
Function.prototype.myBind = function (ctx, ...args) {
ctx = ctx === undefined || ctx === null ? globalThis : Object(ctx);
const key = Symbol();
ctx[key] = this;
return function F(...args2) {
const r = ctx[key](...args, ...args2);
delete ctx[key];
return r;
};
};
const person = {
name: "小明",
};
const methods = function (a, b) {
console.log("[ this ] >", this);
return a + b;
};
const res = methods.myBind(person, 1, 2)();
console.log("[ res ] >", res);
手写 apply
Function.prototype.myApply = function (ctx, args) {
if (Array.isArray(args)) {
ctx = ctx === undefined || ctx === null ? globalThis : Object(ctx);
const key = Symbol();
ctx[key] = this;
const r = ctx[key](...args);
delete ctx[key];
return r;
} else {
throw new Error("myApply方法第二个参数必须为数组类型");
}
};
const person = {
name: "小明",
};
function methods(a, b) {
return a + b;
}
const res = methods.myApply(person, [1, 2]);
console.log("[ res ] >", res);
</script>