一.实现call()方法的原理
Function.prototype.Call = function (ctx, ...args) {
let fn = Symbol(1);
ctx[fn] = this;
ctx[fn](...args);
delete ctx[fn];
};
测试代码:
function show(...args) {
console.log(args);
console.log(this.name);
}
show.Call(
{
name: "mike",
},
"Call",
"Call",
"Call"
);
二.实现apply()方法的原理
Function.prototype.Apply = function (ctx, args = []) {
if (args && !(args instanceof Array)) {
throw "Apply只接受数组作为参数";
}
ctx.fn = this;
ctx.fn(...args);
delete ctx.fn;
};
测试代码:
function show(...args) {
console.log(args);
console.log(this.name);
}
show.Apply(
{
name: "mike",
},
["Apply", "Apply", "Apply"]
);
三.实现bind()方法的原理
Function.prototype.Bind = function (ctx, ...args1) {
return (...args2) => {
ctx.fn = this;
ctx.fn(...args1.concat(args2));
delete ctx.fn;
};
};
测试代码:
function show(...args) {
console.log(args);
console.log(this.name);
}
show.Bind(
{
name: "mike",
},
"Bind1"
);
bind("Bind2", "Bind2", "Bind2");