【问题标题】:Javascript - eval object creation?Javascript - 评估对象创建?
【发布时间】:2012-11-20 11:31:25
【问题描述】:

我对 JavaScript 还是很陌生(虽然不是编码),所以请随意为我挑选和白痴映射。

我试图创建一些可以接受用户输入的东西。如果第一个字符是感叹号,它将尝试使用该名称创建一个对象并运行该对象的“action”方法。否则它会将其视为常规文本(现在是警报)

<script type="text/javascript">
function GetInput(input){

    // Trim the spaces off the beginning and end
    input = input.trim();

    if(input.charAt(0) != "!"){
        // Just some normal text
        alert(input);

        return true;
    }

/* Cut off the exclamation point, replace multiple spaces with one,
 * and get the arguments if any. args[0] = the command. */

    var args = input.substr(1).replace(/\s{2,}/g, " ").split(" ");

// Make sure the function is an object with a method named "action"
    if(eval("typeof "+args[0]+";") === "function"
        && eval("typeof "+args[0]+".prototype.action;") === "function"){

        eval("var command = new "+args[0]+"();");

        command.action(args);
    }else{
        alert('"'+args[0]+'" is not a command.');
    }

    return true;
}
</script>

到目前为止,我注意到的唯一问题是 eval 语句。我知道我可以同时使用 switch/case 并抛弃 eval,甚至可以创建一个包含允许函数名称的数组,并在 eval 之前将输入与该数组进行比较,但我确信一定有更好的方法.

我只想制作对象和方法而不更新任何东西(我认为这是鸭式打字的主要用途之一?)。没有评估这可能吗?如果没有,是否有一种简单的方法来清理字符串的输入以避免诸如“!eval(alert('u b haxed'))”或“!a;alert('u b haxed')”之类的事情?

提前致谢

【问题讨论】:

标签: javascript object eval duck-typing


【解决方案1】:

您应该只使用一次eval 来获取函数,然后在变量中使用它执行所有操作。

var args = input.substr(1).split(/\s+/);
var fn = eval(args[0]);
if (typeof fn == 'function' && typeof fn.prototype.action == 'function') {
    var command = new fn();
    command.action(args);
} else {
    alert('"'+args[0]+'" could not be evaluated to a valid command.');
}

return true;

如果这些构造函数是全局变量,您也可以将它们作为window 对象的属性进行访问:

var fn = window[ args[0] ];

【讨论】:

  • 不应使用eval,因为args[0] 来自用户输入。 windows[args[0]] 更安全。
  • 在这个答案和 TwiNight 的评论之间,我得到了我所需要的。非常感谢你们两个。
  • @TwiNight:一般不会,因为每个用户都可以在自己的浏览器中手动执行恶意代码。 window[args[0]] 不会有任何副作用,但受到更多限制。取决于用户需要什么以及他的经验。
  • 是的,但eval 通常会折旧。
  • @TwiNight eval 远未弃用。 eval 的唯一问题是它经常被没有经验的用户误用和滥用。在许多场景中,使用eval 是完全可以接受的,并且不会带来任何安全风险。不推荐使用意味着他们实际上想从语言中删除该功能,但为了向后兼容,他们保留了它。但是,他们很有可能会在未来的版本中将其删除。 eval 不是这种情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-24
  • 1970-01-01
  • 2019-03-03
  • 2012-02-25
  • 2013-11-26
  • 2022-08-16
相关资源
最近更新 更多