javascript initialize object property

Knight Yoshi picture Knight Yoshi · Oct 20, 2013 · Viewed 9k times · Source

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.

Answer

Hugo Tunius picture Hugo Tunius · Oct 20, 2013

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