Is this use of Javascript eval() 100% safe?

让人想犯罪 __ 提交于 2019-12-05 14:40:26

There is almost zero reasons to use eval and I think that this is not one of them. Remember that all objects act like dictionaries so you can simply do something like this:

var components = {
    component001 : 'testing111',
    component002 : 'testing222',
    component003 : 'testing333'
};

APP.safeEval = function(nameOfComponent) {
    var result = components[nameOfComponent];
    if(result) {
        return result;
    } else {
        return 'ERROR';
    }
}

Well, if all there is is a name, then

  eval(component101)

won't do anything anyway, so it seems safe. Maybe you meant

  return eval(nameOfComponent + '()');

If so, then I don't see why you don't just put your components in a namespace object. Then you wouldn't need eval at all:

  return components[nameOfComponent]();

If they're not functions, then the same thing applies, but you'd leave off the "()".

If the variables are defined in another javascript file and contain only numbers and letters, then they are part of the global namespace. As such, they can be accessed as properties of the window object (no need for eval!):

if (typeof window[nameOfComponent] !== 'undefined')
    return window[nameOfComponent]
return 'ERROR';
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!