Uri Chandler
Uri Chandler

Reputation: 351

Difference between call and prototype.call

In Javascript, is there a reason to prefer

this:

[].forEach.call(...)

over this:

[].prototype.forEach.call(...)

.. ?

Upvotes: 0

Views: 67

Answers (2)

Jani Hartikainen
Jani Hartikainen

Reputation: 43253

The second example won't work, so if we correct it to...

Array.prototype.forEach.call

Now if we compare this against [].forEach.call, the difference is that with the prototype-version, you're not creating a throwaway array object.

Whether or not this makes any difference in practice depends on your specific case. If you're doing this repeatedly hundreds or maybe thousands of times, creating these throwaway array objects can cause higher memory usage and slower GC sweeps in comparison to calling the function directly via the prototype.

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382464

The first one is shorter, thus easier to read and potentially preventing horizontal scrolling.

The second one is buggy as there's no [].prototype (did you mean [].constructor.prototype ?)

The third one would be

Array.prototype.forEach.call(...)

This one is more direct and theoretically faster, as what you get with the first one is indirectly the property that is, in fact, attached to the prototype.

Upvotes: 1

Related Questions