How to workaround renaming of object properties in Closure Compiler?

百般思念 提交于 2019-12-10 23:18:16

问题


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});

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?


回答1:


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.

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;

And in your example:

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:


I just ran into this problem when working with a jquery method requiring object based properties. I solved it by placing all the key names in quotes and then closure compiler didn't mess with them.

So the code above would become:

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


来源:https://stackoverflow.com/questions/15698631/how-to-workaround-renaming-of-object-properties-in-closure-compiler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!