在私有范围的变量中替换eval [英] replacing eval in privately scoped variables

查看:84
本文介绍了在私有范围的变量中替换eval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试删除此函数中的eval语句.我已经习惯了这种(无论如何)样式替换,但是在这种情况下无法解决. 看看:

I'm trying to remove the eval statement in this function. I'm used to the this[whatever] style replacement but it doesn't work out in this instance. Have a look:

var App = (function(fw) {
    var somevar1 = "hello";
    var somevar2 = "world";
    this.get = function(what) {
        return eval(what);
    }
});

var app = new App({some: "thing"});

// now for the use:
console.log(app.get("somevar1"),app);​

在该函数中,例如,我所有的常规评估"选项都无法使用,我不能使用:

In the function, all my normal "eval scrubbing" options are not working for instance, I cant use:

 return this[what]
 return [what]
 return app[what]
 return new Function(what);

当然这不是必须进行评估的奇怪情况吗? .. ps我必须注意,我无法重新检查App内部的变量,因为它是庞大代码库的一部分.

surely this isn't an odd case where eval is necessary? .. ps I have to note that I CANNOT rescope the variables inside App as it's part of a huge codebase.

这里有一些有趣的东西:

Here's something to fiddle with:

http://jsfiddle.net/xAVYa/

推荐答案

不幸的是,您不走运; eval唯一可以访问此类变量的东西.下次,不要那样做:)

Unfortunately, you're out of luck; eval is the only thing that can access variables like that. Next time, don't do things that way :)

您可以通过保留data对象来开始迁移:

You can start a migration by keeping a data object:

var App = (function(fw) {
    var data = {
        somevar1: "hello",
        somevar2: "world"
    };

    this.get = function(what) {
        return data[what];
    };
});

然后逐步在您看到的整个代码库中执行此操作.它应该不会破坏任何东西.

And just gradually do this across the entire codebase where you see it. It shouldn't break anything.

这篇关于在私有范围的变量中替换eval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆