我不是在问如何使用它。我知道如何使用它。
但是当 apply 调用调用它的函数时,它究竟是如何将一个参数数组传递给一个函数,而这个函数并不是为一个参数编写的?它是否将给定的参数数组与调用的函数“arguments”结合起来?
我查看了 .apply 和 .call 的最新 ECMAscript 规范,但我并没有真正看到任何关于底层逻辑的信息。
欢迎任何解释。我是 JavaScript 的新手,想更好地了解幕后发生的事情。我目前正在尝试自己重新创建一些基本功能,而这个给我带来了很多麻烦。
最佳答案
来自spec .
我们必须获取 argArray 并创建参数对象伪数组。
本质上
Function.prototype.apply = function apply (thisArg, argArray) {
var len = argArray.length;
var n = ToUint32(len);
var argList = []; // where this is a List not an array.
var index = 0;
var indexName;
var nextArg;
while (index < len) {
indexName = ToString(index);
nextArg = argArray[indexName];
argList.push(nextArg);
index++;
}
return this['[[Call]]'](func, thisArg, argList); // ignore the syntax however
// This is the line where the function
// will be called and provide
// the thisArg and thisArray
}
我省略了一些发生的类型检查,但这基本上与规范规定的 Function.prototype.apply
的实现方式非常接近。在调用函数之前,我们制作了自己的对象并构建了 argList
。
重要的是要注意。名为 [[Call]]
的内部方法不同于 Function.prototype.call
。
关于javascript - JavaScript .apply 方法如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34802982/