Ryler Sturden
Ryler Sturden

Reputation: 354

Calling instance function on each object in array

I have an array of objects that contain instance methods. I can iterate over each object and call it specifically like this:

items.forEach(function(i) { i.show(false) });

But I was hoping for a less verbose version like the following, which does not work.

items.forEach.show(false);

or even

items.show(false);

Is there a cleaner way to do it?

Upvotes: 0

Views: 238

Answers (1)

Dmitri Pavlutin
Dmitri Pavlutin

Reputation: 19110

1) The shortest way is using ES 6 arrow functions:

items.forEach(i => i.show(false));

2) Use a helper function:

function iterator(i) { 
  i.show(false) 
}

items.forEach(iterator);

3) Define a generator:

function gen() {
   var funcName = arguments[0],
     params = Array.prototype.slice.call(arguments, 1);
   return function(item) {
      item[funcName].apply(item, params);
   };
}

items.forEach(gen('show', false));     // -> i.show(false);
items.forEach(gen('show', true));      // -> i.show(true);
items.forEach(gen('delete', 1, true)); // -> i.delete(1, true);

Upvotes: 2

Related Questions