Como isso converte document.querySelectorAll('a')de uma
NodeList matriz para uma matriz regular?
Este é o código que temos,
[].slice.call(document.querySelectorAll('a'), 0)
Vamos desmontá-lo primeiro,
[] // Array object
.slice // Accessing the function 'slice' present in the prototype of Array
.call // Accessing the function 'call' present in the prototype of function object(slice)
(document.querySelectorAll('a'),0)
// 'call' can have arguments like, (thisArg, arg1,arg2...n).
// So here we are passing the 'thisArg' as an array like object,
// that is a 'nodeList'. It will be served as 'this' object inside of slice function.
// And finally setting 'start' argument of slice as '0' and leaving the 'end'
// argument as 'undefined'
Etapa: 1 Execução da callfunção
- Dentro
call, além do thisArg, o restante dos argumentos será anexado a uma lista de argumentos.
- Agora a função
sliceserá invocada vinculando seu thisvalor como
thisArg(o objeto semelhante ao array veio document.querySelector) e com a lista de argumentos. ie] argumento startque contém0
Etapa: 2 Execução da slicefunção chamada dentro docall
startserá atribuído a uma variável scomo0
- desde que
endseja undefined, this.lengthserá armazenado eme
- uma matriz vazia será armazenada em uma variável
a
Depois de fazer as configurações acima, a seguinte iteração ocorrerá
while(s < e) {
a.push(this[s]);
s++;
}
- a matriz preenchida
aserá retornada como resultado.
PS Para uma melhor compreensão do nosso cenário, algumas etapas necessárias para o nosso contexto foram ignoradas no algoritmo original de chamada e fatia .
Array.prototype.slice.call(document.querySelectorAll('a'));é uma maneira adequada de escrever o pedaço de código que você escreveu.