手动实现call、apply、bind
实现call
Function.prototype.myCall = function (context, ...args) {
context = context || window;
console.log("myCall", context);
context._fn_ = this;
let result = context._fn_(...args);
delete context.fn;
return result;
}
Function.prototype.myCall2 = function (context) {
context = context || window;
let fn = Symbol();
let args = [...arguments].slice(1);
context[fn] = this;
let result = context[fn](...args);
delete context[fn];
return result;
}
let Person_Call = {
name: "Tom",
say: function (...args) {
console.log(this)
console.log(`我叫${this.name},我今年${args[0]},我的工作是${args[1]}`)
}
}
let person1 = {
name: "Jack"
}
Person_Call.say.myCall(person1, 19, "老师");
实现call
Function.prototype.myApply = function (context) {
context = context || window;
let fn = Symbol();
let args = [...arguments].slice(1);
context[fn] = this;
let result = context[fn](args);
delete context[fn];
return result;
}
let Person_Apply = {
name: "Tom",
say: function (args) {
console.log(this)
console.log(`我叫${this.name},我今年${args[0]},我的工作是${args[1]}`)
}
}
let person1 = {
name: "Jack"
}
Person_Apply.say.myApply(person1, [19, "医生"])
实现bind
Function.prototype.myBind = function (context) {
let self = this
let arg = [...arguments].slice(1)
return function () {
let newArg = [...arguments]
console.log(newArg)
return self.apply(context, arg.concat(newArg));
}
let Person_Bind = {
name: "Tom",
say: function (...args) {
console.log(this)
console.log(`我叫${this.name},我今年${args[0]},我的工作是${args[1]}`)
}
}
let person1 = {
name: "Jack"
}
var per = Person_Bind.say.myBind(person1, 20, "律师");
per();