rPa*_*Pat 6 javascript callback call apply
我不是在问如何使用它。我知道如何使用它。
但是当 apply 调用调用它的函数时,它究竟是如何将一个参数数组传递给一个没有写入参数数组的函数呢?它是否将其给定的参数数组与被调用的函数“参数”组合在一起?
我查看了 .apply 和 .call 的最新 ECMAscript 规范,但我并没有真正看到有关底层逻辑的任何内容。
欢迎任何解释。我是 JavaScript 新手,想更好地了解幕后发生的事情。我目前正在尝试自己重新创建一些基本功能,而这个功能给我带来了很多麻烦。
从规格来看。
我们必须获取 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
}
Run Code Online (Sandbox Code Playgroud)
我省略了一些发生的类型检查,但这本质上非常接近规范所规定的Function.prototype.apply
实现方式。argList
我们制作自己的对象并在调用函数之前构建它。
值得注意的是。名为的内部方法[[Call]]
不同于Function.prototype.call
.