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)
}
}
evalis completely unnecessary for this case, just use the bracket notation to access the dynamically named property:Notes:
object(you were using=, instead of:).varstatement to declareobjectnorgetData, please, when declaring variables, use thevarstatement, 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.: