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.

2 Answers 2

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

Comments

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.