【问题标题】:Problem with eval and google closure compilereval 和 google 闭包编译器的问题
【发布时间】:2011-04-14 12:28:54
【问题描述】:

我正在使用 google 闭包来压缩我的代码,但我对以下代码行有疑问:

        eval('this.find(\''+ element_to_append_the_controller+ '\').'+controller_to_load+'(options_for_controller)');

我必须使用 eval,因为我必须在元素上执行的方法 (controller_to_load) 是可变的,并且取决于我得到的参数。

我的问题是我必须将一个对象传递给该方法,所以我将其作为变量名的字符串表示形式(options_for_controller),但闭包会更改该名称并且不会更改变量我的 eval 字符串中的名称。

我的解决方案是:

  • 以字符串形式动态获取变量名
  • 将对象(带有回调函数)解析为字符串
  • 对这些代码行禁用压缩

但是我该怎么做呢?还是有其他解决方案?

谢谢

【问题讨论】:

    标签: javascript eval google-closure-compiler


    【解决方案1】:

    有些程序员使用 eval 是因为他们没有意识到可以写 eval('a.' + b) 而不是写 a[b]

    试试这个而不是你的 eval()

    this.find(element_to_append_the_controller.toString())[controller_to_load](options_for_controller);
    

    【讨论】:

    • 谢谢,你的权利,用这种类型的动态执行替换了所有的 eval,太棒了。
    【解决方案2】:
    this.find(element_to_append_the_controller.toString())[controller_to_load](options_for_controller)
    

    AKA 不要使用 eval。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多