4
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?

3
  • Why isn't imgs an array? Wouldn't it be simpler? Commented Mar 29, 2018 at 9:50
  • You can iterate the imgs values. Please share your attempt first. Commented Mar 29, 2018 at 9:51
  • @Quentin maybe the dup is an answer to OP's question, but it isn't going to really help them, because the question is more or less based on ... say on a wrong assumption. Commented Mar 29, 2018 at 9:55

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.