3
var imgs = {
    a: function(){
        //...
    },
    b: function(){
        //...
    },
    c: function(){
        //...
    }
};
var preloadImgs = function(){
    imgs.a();
    imgs.b();
    imgs.c();
};
preloadImgs();

Is there a way to automate preloadImgs so it loads all the methods inside imgs at once, instead of me having to type every single one?

Magdi Gamal
  • 681
  • 1
  • 9
  • 25

2 Answers2

4

Use Object.values

Object.values( imgs ).forEach( s => s() );

Demo

var imgs = {
    a: function(){
       console.log("1");
    },
    b: function(){
       console.log("2");
    },
    c: function(){
       console.log("3");
    }
};
var preloadImgs = function(){
    Object.values( imgs ).forEach( s => s() );
};
preloadImgs();

Edit

If all the values in imgs are not function, then you can apply the filter first

Object.values( imgs )
  .filter( s => typeof s === 'function' ) //filter out values which are function
  .forEach( s => s() ); //execute those functions
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
3

Loop over all the values of the imgs object and call it if its a function

var imgs = {
    a: function(){
        console.log('a');
    },
    b: function(){
        console.log('b');
    },
    c: function(){
        console.log('c');
    }
};
var preloadImgs = function(){
    Object.values(imgs).map(value => {
      if(typeof value === 'function') {
          value.call();
      }
    })
};
preloadImgs();
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400