本文介绍了如何解决在Closure Compiler中重命名对象属性的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a JS library that uses has something like the following method:

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函数,如:

But after advanced optimization objects properties name, arg1 and arg2 will be a, b, c, so I can't get them in doAction handler. I know I can to use quotes for a property names to prevent it from changing, but is there any better approach like special util function like:

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

可以保存对象属性名称吗?

that allows me to save object property names?

推荐答案

所有属性均应重命名.例如,您的示例编译为:

The properties should all be renamed consistently. For instance your example compiled to:

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

您可以看到,这些属性是以不间断的方式重命名的.除非启用了实验性的基于类型的优化,否则这种情况始终是这种情况,但即使这样,这种情况也应得到适当处理.

You can see that the properties were renamed in a non-breaking fashion. This behaviour is always the case unless the experimental type-based optimizations are enabled, but even then this specific case should be properly handled.

如果您需要绝对不重命名属性,则可以在extern文件中定义一个接口,然后将类型转换为该类型.

If you need the properties to absolutely not be renamed, you can define an interface in an extern file and type cast your methods to be of that type.

/** @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}));

这篇关于如何解决在Closure Compiler中重命名对象属性的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 21:36