I’d like to do something like the following w/o using eval(). What’s the best way to do that?
config: function(config) {
for (var key in config) {
if (config.hasOwnProperty(key)) {
console.log('setting: ' + key + ' = ' + config[key]);
eval(key + ' = "' + config[key] + '"');
}
}
}
You don’t have JSON. You have a normal JavaScript object. You can make the keys to global variables by setting them as properties of the
windowobject (all global variables are properties of thewindowobject and usingevalmakes them global):But note that this might overwrite already set values or even nativ
windowproperties. To avoid this, you might want to test whether the property already exists first:As global variables are bad, it might be better to assign the properties only to the object where the
configfunction is defined on. This would bethis[key] = config[key]if you call the function withobj.config(someConfiguration).In any way you have to assign them to some object. You cannot make them local to a function otherwise. In the end it depends on where you want to have access to the configuration values.