Explanation of [].slice.call in javascript?
Solution 1:
What's happening here is that you call slice()
as if it was a function of NodeList
using call()
. What slice()
does in this case is create an empty array, then iterate through the object it's running on (originally an array, now a NodeList
) and keep appending the elements of that object to the empty array it created, which is eventually returned. Here's an article on this.
EDIT:
So it starts with an empty array [], then slice is used to convert the result of call to a new array yeah?
That's not right. [].slice
returns a function object. A function object has a function call()
which calls the function assigning the first parameter of the call()
to this
; in other words, making the function think that it's being called from the parameter (the NodeList
returned by document.querySelectorAll('a')
) rather than from an array.
Solution 2:
In JavaScript, methods of an object can be bound to another object at runtime. In short, javascript allows an object to "borrow" the method of another object:
object1 = {
name: 'Frank',
greet() {
alert(`Hello ${this.name}`);
}
};
object2 = {
name: 'Andy'
};
// Note that object2 has no greet method,
// but we may "borrow" from object1:
object1.greet.call(object2); // Will show an alert with 'Hello Andy'
The call
and apply
methods of function objects (in JavaScript, functions are objects as well) allows you to do this. So, in your code you could say that the NodeList is borrowing an array's slice method. .slice()
returns another array as its result, which will become the "converted" array that you can then use.