Best way to "shortcut" a prototype method?

Say I’m trying to create a shortcut function allowing HTMLCollections to call Array.prototype.forEach() with ease.

Which one of these ways would be best?

HTMLCollection.prototype.forEach = Array.prototype.forEach;
const forEachX = function(args) {
    return Array.prototype.forEach.call(this, args);
}
const forEachX = function() {
    return Array.prototype.forEach.apply(this, arguments);
}

BTW:

  • Will these actually work and work well?
  • Does this count as polyfill?
  • For the latter two cases, I suppose I shouldn’t just name the custom function forEach should I?
  • For the latter two cases, is there a naming convention / recommended naming for this kind of things?

Thanks~

Have you tested any of these yet? You should be able to tell us if they work :slight_smile: Also, how are you planning on calling the second and third functions in your code?

I would say no. Polyfills are generally used to provide newer functionality in browsers that don’t yet support it. There is no forEach method for HTMLCollections, so no browsers support it because it doesn’t exist and thus you aren’t creating a polyfill, you are creating new functionality.

Also, just in case you weren’t aware, you can iterate over an HTMLCollection using a for...of loop. I suppose I can see an argument for extending the prototype in the first method so you get slightly more concise code that mimics Array.forEach (although not everyone thinks that is a good idea), but I’m not sure I see any advantages to the second or third methods. And I wouldn’t bother with the third method. Nobody uses arguments any more.

1 Like

Right… I just realised to call them I still need to do forEachX.call(), in which case they may as well be

const forEachX = Array.prototype.forEach;

and still no better than the first way.

Thanks!

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