apply 和 call 是 javaScript 内置的函数方法,其作用就是来改变函数执行的时候内部 this 指向的,这两个函数的功能是一样的,只是接收参数有所不同,他们第一个参数都是一个对象也就是函数调用的时候 this 指向的上下文对象,apply 接收的第二个参数是个数组集合,而 call 则是以多个参数的形式传递的。
首先我们定义一个函数和一个对象
function picker() {
console.log(this.name, arguments);
}
const obj = {
name: 'JS 基础实现 apply、call',
};
先看 apply 的写法
Function.prototype.myApply = function (context, args) {
context = typeof context === 'object' ? context : window;
args = args || [];
const key = Symbol();
context[key] = this;
const result = context[key](args);
delete context[key];
return result;
}
picker.myApply(obj, [1, 2, 3]);
下面是 call 的写法
Function.prototype.myCall = function (context, ...args) {
context = typeof context === 'object' ? context : window;
const key = Symbol();
context[key] = this;
const result = context[key](...args);
delete context[key];
return result;
}
picker.myCall(obj, 1, 2, 3);