I want to loop through an object and run all functions called init().
I have the following code but it is repetitive. How do I effectively make MC and Su instances of a variable?
Here is the repetitive code.
MC.initAll = function() {
for ( var key in MC ) {
if( MC.hasOwnProperty( key ) ) {
if( MC[key].hasOwnProperty( 'init' ) ) {
MC[key].init();
}
}
}
for ( var key in Su ) {
if( Su.hasOwnProperty( key ) ) {
if( Su[key].hasOwnProperty( 'init' ) ) {
Su[key].init();
}
}
}
}
There are many options…
-
Put them in an array and then pop them out via a for loop.
-
Make them object properties and loop through the object properties.
-
Make a function call and pass them in as parameters.
-
Use an Object Map per fritz below
Which is best or is there a better way?
Try