为什么Array.prototype.map.call而不是Array.map.call [英] why Array.prototype.map.call instead of Array.map.call
问题描述
我遇到了一些代码,其中的人使用 Array.prototype.map.call
而不是 Array.map.call
:
I fell upon some lines of code where the guy uses Array.prototype.map.call
instead of Array.map.call
:
function getLinks() {
var links = document.querySelectorAll('h3.r a');
return Array.prototype.map.call(links, function(e) {
return e.getAttribute('href');
});
}
为什么不简单地调用 Array.map.call
?我检查了Firefox控制台, Array
和 Array.prototype
都有map功能。是否存在差异?
Why not simply calling Array.map.call
? I checked on the Firefox console and both Array
and Array.prototype
have the map function. Is there a difference ?
推荐答案
这是因为 document.querySelectorAll
不返回 Array
实例但是 NodeList
的实例(或者至少不保证返回<$ c $所有浏览器上的c> Array 。
NodeList
具有索引元素,但不包括 Array
原型中的所有方法。
This is because document.querySelectorAll
does not return an Array
instance but an instance of NodeList
(or at least is not guaranteed to return an Array
on all browsers).
NodeList
has indexed elements but does not include all methods from the Array
prototype.
这就是我们需要从数组
中调用 map
方法的原因在返回对象的上下文中的原型。
This is why we need a hack calling map
method from Array
's prototype in the context of the returned object.
我假设您理解为:
var a = [], f = function() {};
表达式:
a.map(f);
相当于:
Array.prototype.map.call(a, f);
参见:
- 为什么document.querySelectorAll会返回StaticNodeList而不是真正的数组?
- https:// developer .mozilla.org / zh-CN / docs / Web / API / Document.querySelectorAll
- https://developer.mozilla.org/en-US/docs/Web/API/NodeList
- Why does document.querySelectorAll return a StaticNodeList rather than a real Array?
- https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll
- https://developer.mozilla.org/en-US/docs/Web/API/NodeList
这篇关于为什么Array.prototype.map.call而不是Array.map.call的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!