一、call函数介绍
call:用于调用一个函数,并且可以设置函数内部的this值,以及传递一个或多个参数给该函数
用法:
func.call(thisArg, arg1, arg2, ...)
二、实现call函数
本质:给传入的thisArg添加一个方法
Function.prototype.myCall = function (context, ...args) {
//函数调用者要是函数,才能用原型链上的方法
if (typeof this !== "function") {
throw new Error("error");
}
//若没有传递thisarg,则默认是window
context = context || window;
//this指向的是调用call的那个函数,也就是下面例子中的getName
context.fn = this;
const result= context.fn(...args)
//避免影响原来的对象,必须要删除刚刚添加的属性
delete context.fn
return result;
};
使用
var name = "gggg";
const p = {
name: "hhhh",
getName: function () {
console.log(this.name);
},
};
const person = {
name: "zs",
};
console.log(p.getName.myCall(person));//zs