Javascript 如何解决在闭包编译器中重命名对象属性的问题?
我有一个JS库,它使用如下方法:Javascript 如何解决在闭包编译器中重命名对象属性的问题?,javascript,obfuscation,google-closure-compiler,Javascript,Obfuscation,Google Closure Compiler,我有一个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}); 但是在高级优化对象属性name之后,arg1和arg2将是a,b,c,因此我无法在doAction处理程序中获取它
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});
但是在高级优化对象属性name
之后,arg1
和arg2
将是a
,b
,c
,因此我无法在doAction
处理程序中获取它们。我知道我可以对属性名称使用引号来防止其更改,但有没有更好的方法,如特殊的util函数,如:
this.trigger('doAction', MYAPP.util.intoObject{name: 'write', arg1: 1, arg2: 2});
允许我保存对象属性名称吗?所有属性都应一致重命名。例如,您的示例编译为:
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}));
我在使用需要基于对象的属性的jquery方法时遇到了这个问题。我解决了这个问题,把所有的键名都放在引号里,然后闭包编译器就不会弄乱它们了 因此,上述代码将变为:
this.trigger('doAction', {'name': 'write', 'arg1': 1, 'arg2': 2});