跳到主要内容

call

2024年03月12日
柏拉文
越努力,越幸运

一、认识


Function.prototype.call() 方法会以给定的 this 值和逐个提供的参数调用该函数。 这个函数几乎与 apply() 相同,只是函数的参数以列表的形式逐个传递给 call(),而在 apply() 中它们被组合在一个对象中,通常是一个数组——例如,func.call(this, "eat", "bananas")func.apply(this, ["eat", "bananas"])

二、语法


call(thisArg)
call(thisArg, arg1)
call(thisArg, arg1, arg2)
call(thisArg, arg1, arg2, /* …, */ argN)
  • thisArg: 在调用 func 时要使用的 this 值。如果函数不在严格模式下,nullundefined 将被替换为全局对象,并且原始值将被转换为对象。

  • arg: 函数的参数。

三、返回值


使用指定的 this 值和参数调用函数后的结果。

四、实现原理


Function.prototype.myCall = function (thisArg, ...argArray) {
const fn = this;
if (thisArg) {
thisArg = Object(thisArg);
} else {
thisArg = typeof window === "undefined" ? global : window;
}
thisArg.fn = fn;
const result = thisArg.fn(...argArray);
delete thisArg.fn;
return result;
};

function foo(name, age) {
console.log(this);
console.log(name, age);
}
const obj = {
name: "柏拉图",
age: 23,
};
foo.myCall(null, "哈哈哈", 32);