1

I need to selectively run several functions depending on various situations. I have a basic object like this:

object = {
  whatever : {
    objects : null
  },
  something : {
    objects : // some object
  }
};

I need to iterate through the object values and if objects is not null, I need to run a specific function. If whatever.objects is not null, I need to run whateverFunction();. If something.objects is not null, I need to run somethingFunction();.

for( i in object )
{
  if ( object[i].objects )
    // run a certain function
}

What is the best way to run these artibtrarily named functions based off of the values in the object? I could store the name of the "function-to-be-run" in the object and eval() it, but I'd like to try to avoid evaling.

Would it make more sense to create an class object each with it's own function to be run, and if so, how would I do this?

2 Answers 2

5
object = {
  whatever : {
    objects : null,
    func : whateverFunction
  },
  something : {
    objects : // some object,
    func : somethingFunction
  }
};

for (var i in object) {
  if (object[i].objects) {
    objects[i].func();
  }
}

Functions are themselves objects which can be passed around and stored. No need to store the function's name; store the function itself.

Sign up to request clarification or add additional context in comments.

4 Comments

For reference: functions are themselves objects, so can be passed around and stored. So, no need to store the function's name; store the function itself. (If the situation allows, that is.)
@Matchu Haha, I was working on that explanation but you beat me to it.
does the function have to be defined here in the object? Or can it be defined elsewhere? I have some rather large complicated functions that would make the object pretty messy.
@Jakobud "func : somethingfunc" is just a property assignment. The keyword somethingfunc can be a function you defined elsewhere in your program. Note that this is very easy to test for yourself, just start up rhino.
1

If whateverFunction() and somethingFunction() are global, try something like this

var funcName = 'somethingFunction';

window[funcName]();

Comments

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.