我们知道,call和apply方法有效解决通过继承的方式来获取js内置方法(或某些封装完善对象的方法)产生的性能损耗,在这里面,看过call或者apply源码的朋友,我想最大的一个疑问就是:
我们来看一个关于call方法的内部实现和一个关于call的引用:context.fn = this 一开始肯定疑惑this到底指向谁?
1、下面是call方法的模拟实现:
Function.prototype.call = function (context) {
context = context ? Object(context) : window;
context.fn = this;
let args = [...arguments].slice(1);
let result = context.fn(...args);
delete context.fn
return result;
}
2、下面是call方法的简单调用例子:
var value = 1;
var foo = {
value: 1
};
function bar() {
console.log(this.value);
}
bar.call(foo); // 1