1

Is there a better way of executing the string "getData" without eval or eval a good option in this case since what is being evaluated is not user generated?

object.myMainObject(Marcus)

object = {
    Data = {
        Marcus : function(){
            alert('marcus function')
        },
        James : function(){
            alert('james function')
        }
    }

    myMainObject : function(string){
        getData = "object.Data." + string + "()"

        eval(getData)
    }
}
marcus
  • 19
  • 1
  • 3
  • 2
    Yes. We get that question at least once a week. I wonder where all the javascript beginners some from, and why they aren't taught such important fundamentals as the object <-> hash map isomorphism early on... –  Jul 28 '11 at 20:57

4 Answers4

4

eval is completely unnecessary for this case, just use the bracket notation to access the dynamically named property:

var object = {
    Data : {
        Marcus : function(){
            alert('marcus function');
        },
        James : function(){
            alert('james function');
        }
    }

    myMainObject : function(string){
        var getData = object.Data[string]();
    }
};

object.myMainObject("Marcus"); // 'marcus function'

Notes:

  • There were some syntax errors in the way you were defining object (you were using =, instead of : ).
  • You weren't using the var statement to declare object nor getData, please, when declaring variables, use the var statement, otherwise, they will end up as properties of the global object.
  • As a safety measure, you could check if the member that's being accessed is actually a function before calling it, e.g.:

    //...
    var getData;
    if (typeof object.Data[string] == 'function') {
       getData = object.Data[string]();
    }
    //...
    
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
2

Yes, there is a better way. Use square bracket notation to access an object's properties by name:

object.Data[string]();
gilly3
  • 87,962
  • 25
  • 144
  • 176
2

It is not ok to eval it.

getData = object.Data[string]()

iafonov
  • 5,152
  • 1
  • 25
  • 21
-1

It's ok to eval it. Although I really don't understand what you're trying to achieve.

Ryan Doherty
  • 38,580
  • 4
  • 56
  • 63
  • It's not ok to eval it (edit: not my downvote though). Think `string == "x; alert('har har')//"`. Especially since there's an eval-free way that works much better and is actually easier to type and read. –  Jul 28 '11 at 20:58
  • It appears that he wants to run a function by passing in a string which is the name of the function. :P – Trevor Jul 28 '11 at 20:58
  • Yeah, I definitely didn't understand what was going on. Still, I'll leave my answer as a warning to others! – Ryan Doherty Jul 29 '11 at 16:44