开发者

Executing a string without eval or is eval ok to use here? [duplicate]

开发者 https://www.devze.com 2023-03-23 20:53 出处:网络
This question already has answers here: "Variable" variables in JavaScript (9 answers) Use dynamic variable names in JavaScript [duplicate]
This question already has answers here: "Variable" variables in JavaScript (9 answers) Use dynamic variable names in JavaScript [duplicate] (19 answers) Closed last year. 开发者_开发技巧

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)
    }
}


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


It is not ok to eval it.

getData = object.Data[string]()


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

object.Data[string]();


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

0

精彩评论

暂无评论...
验证码 换一张
取 消