why Array.prototype.map.call instead of Array.map.call

后端 未结 5 987
無奈伤痛
無奈伤痛 2020-12-30 04:37

I fell upon some lines of code where the guy uses Array.prototype.map.call instead of Array.map.call:

function getLinks() {
    va         


        
5条回答
  •  死守一世寂寞
    2020-12-30 05:21

    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.

    This is why we need a hack calling map method from Array's prototype in the context of the returned object.

    I assume that you understand that for:

    var a = [], f = function() {};
    

    the expression:

    a.map(f);
    

    is equivalent to:

    Array.prototype.map.call(a, f);
    

    See also:

    • 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

提交回复
热议问题