1,实现过程:
//在原型上自定义一个myCall
Function.prototype.myCall = function (thisArg, ...res) {
//保存一下刚开始调用myCall的主体中的this(指向的是一个函数)
let fn = this;
//为了防止传入的参数是数字或字符串无法添加属性,给从传入的参数转换为对象
thisArg = thisArg ? Object(thisArg) : window;
//当传递了参数时,给参数添加一个属性,让属性等于刚开始存的函数,相当于修改了fn中的this指向thisArg
thisArg.fn = fn;
//相当于又来了一次隐式绑定。在thisArg身上调用fn,此时this就会指向thisArg
const result = thisArg.fn(...res);
//因为我们为了改变this给thisArg添加了一个属性fn,用完之后清除一下
delete thisArg.fn;
//将调用函数后得到的返回值返回出去
return result;
};
function foo(name, sex) {
this.name = name;
this.sex = sex;
console.log("foo被调用了");
console.log(this);
}
const person = {
age: "18"
};
//foo.myCall属于隐式绑定,当被调用时myCall中的this就是foo中的this
foo.myCall(person, "ls", "女"); //
案例二:
//说到底call内部实现是通过,给call函数中传入的对象添加一个属性等于调用call的那个函数。
//这样调用call函数中的this的指向就会指向传入的对象
const a = {
name: "zs",
hobby() {
console.log(this); //ls
}
};
const b = {
name: "ls",
play: a.hobby //ls
};
b.play();