2

This is going to be stupid, but... I for the life of me can't figure out how to initialize all the methods of an object. For instance

var obj = {
prop1: function() { ... },
prop2: function() { ... } //etc
}

Can't figure out how to initialize them without calling obj.prop1() and obj.prop2(), which would be vary tedious if I have ya'know 10+ functions. I've also looked at something like,

var obj = new obj();

function obj() {
    this.init=function() { ... };
    this.init();
}

However, as far as I can tell, again, I'd have to initialize each one independently.

Knight Yoshi
  • 924
  • 3
  • 11
  • 32

2 Answers2

1

I don't really understand why you would ever need to initialize 10 different things for a single object.

One way to do this is hide all the calls in a single init method, but you would still have to run all 10 methods from there.

The other way is to name all initializing methods something special like __initMyCustomInit. After that you can loop over all the properties of the object and match __init using the regex ^__init.*$

for (var prop in obj) {
  if (obj.hasOwnProperty(prop) && prop.match(/^__init.*$/)) {
    obj[prop]();
  }
}
Hugo Tunius
  • 2,869
  • 24
  • 32
0

I'm not sure if I understand fully what you want but this could work:

var obj = {

prop1: function() { return true; },
prop2: function() { return false; }

}
//init
for(var r in obj){
      obj[r](); // call!
}

Or as part of your obj:

var obj = {
  prop1: function() { return true; },
  prop2: function() { return false; },
  init: function() {
     for(var r in this){
         //prevent calling your self...
         if (r!=='init'){
           this[r]();
         }
     } 
  }   
}

obj.init();
rene
  • 41,474
  • 78
  • 114
  • 152
  • This init method you use here, you only use for singleton objects like above? I assume when you are not using singleton objects, such as when you want inheritance, you would use the new syntax e.g. var obj = new MyObject(); – Donato Oct 29 '14 at 18:44