【问题标题】:How to workaround renaming of object properties in Closure Compiler?如何解决在 Closure Compiler 中重命名对象属性的问题?
【发布时间】:2013-03-29 06:39:59
【问题描述】:

我有一个 JS 库,它使用类似以下方法:

this.on('doAction', function (args) {
   console.log(args.name);
   console.log(args.arg1 + ' ' 9 args.arg2);
});
this.trigger('doAction', {name: 'write', arg1: 1, arg2: 2});

但是经过高级优化对象属性namearg1arg2 将是abc,所以我无法在doAction 处理程序中获取它们。我知道我可以在属性名称中使用引号来防止它发生变化,但是有没有更好的方法,比如特殊的 util 函数:

this.trigger('doAction', MYAPP.util.intoObject{name: 'write', arg1: 1, arg2: 2});

这允许我保存对象属性名称?

【问题讨论】:

    标签: javascript obfuscation google-closure-compiler


    【解决方案1】:

    所有属性都应该一致地重命名。例如,您的示例编译为:

    this.c("doAction", function(a) {
      console.log(a.name);
      console.log(a.a + " " + a.b)
    });
    this.d("doAction", {name:"write", a:1, b:2});
    

    您可以看到属性以非中断方式重命名。除非启用了实验性的基于类型的优化,否则这种行为总是如此,但即使这样,也应该正确处理这种特定情况。

    如果您需要绝对不重命名属性,您可以在外部文件中定义一个接口并将您的方法类型转换为该类型。

    /** @externs */
    /** @interface */
    function myInterface() {}
    /** @type {number} */
    myInterface.prototype.arg1 = 0;
    

    在你的例子中:

    this.on('doAction', /** @param {myInterface} args */  function (args) {
       console.log(args.name);
       console.log(args.arg1 + ' ' + args.arg2);
    });
    this.trigger('doAction',
      /** @type {myInterface} */ ({name: 'write', arg1: 1, arg2: 2}));
    

    【讨论】:

      【解决方案2】:

      我在使用需要基于对象的属性的 jquery 方法时遇到了这个问题。我通过将所有键名放在引号中来解决它,然后闭包编译器没有弄乱它们。

      所以上面的代码会变成:

      this.trigger('doAction', {'name': 'write', 'arg1': 1, 'arg2': 2});
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-10-23
        • 1970-01-01
        • 2021-02-16
        • 2011-11-10
        • 2014-04-15
        • 2018-06-28
        • 2017-08-18
        相关资源
        最近更新 更多