Knight Yoshi
Knight Yoshi

Reputation: 994

javascript initialize object property

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.

Upvotes: 2

Views: 10593

Answers (2)

Hugo Tunius
Hugo Tunius

Reputation: 2879

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

Upvotes: 1

rene
rene

Reputation: 42473

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

Upvotes: 0

Related Questions