Call method within prototype object

Hello,

Consider following code:

let elements = document.querySelectorAll(".test"); // selecting all HTML elements with class of 'test'm return array-like object
let elementsArray = Array.prototype.slice.call(elements); // convert array-like object to array

So whats the difference between this:
let elementsArray = Array.prototype.slice.call(elements);

and this:
let elementsArray = Array.slice.call(elements);

How calling some method from prototype object helps?

Array.prototype.slice exists, and Array.slice doesn’t exist.

When you create an object (which an array is), such as with:

var tempArray = [1, 2, 3];

the prototype of the tempArray points to the Array object.


source: https://www.kirupa.com/html5/extending_built_in_objects_javascript.htm

When you ask tempArray for its slice method, JavaScript: checks tempArray to see if it has a method called slice. If it doesn’t find one there, it follows the prototype reference, and checks Array for that method, where it does find the slice method.

If you asked for something that doesn’t exist, such as tempArray.foobar(), tempArray, Array, and Object are all checked for the foobar method, and when it cannot find it you’re told that it’s undefined.

2 Likes

Thank you very much for explanation sir!

1 Like

It might also be worth pointing out that ES6 gives us:

const elementsArray = Array.from(elements);

and even:

const elementsArray = [...elements];

Which do the same thing, but with a far more readable syntax.

1 Like

Thanks, I know for that but its not supported in IE 11.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.