1. call() 方法调用者(MemberExpression)是一个函数体 (this的值) 所以 可以将该函数体 赋值给目标对象的一个属性 , 这样该对象就有了这个方法
2. 调用该方法传入可选参数
3. 删除掉 赋值给 该对象的自定义方法
Function.prototype.myCall = function (targetObj, paramter) {
targetObj.fn = this; // 1. 将要调用的函数体 赋值给目标对象的属性
targetObj.fn(...paramter) // 2. 目标对象调用该方法
delete targetObj.fn; // 3. 删除之前赋值给目标对象的方法
}
// 思考: 假如该对象上已经有了 fn 属性 ,那上面的代码是不是会将原有的值覆盖掉 ???, 所有我们该如何解决呢?
// 通过 Es6 的Symbol来解决这个问题
Function.prototype.my_Call = function (context, paramter) {
if (typeof context === "object") {
context = context || window;
} else {
Object.create(null)
}
let fn = Symbol()
context[fn] = this;
const result = context[fn](paramter);
delete context.fn;
return result;
}
const obj = {
name: "wade",
sayHello(params) {
console.log(` ${this.name}:hello,请你吃${params}`)
}
}
const obj1 = {
name: 'Andy'
}
obj.sayHello.my_Call(obj1, '糖');