在编译时删除代码块

在编译时删除代码块

本文介绍了Google Closure编译器高级:在编译时删除代码块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我采用这段代码并进行编译(高级优化)

If I take this code and compile it (advanced optimizations)

/**@constructor*/
function MyObject() {
    this.test = 4
    this.toString = function () {return 'test object'}
}
window['MyObject'] = MyObject

我得到了这段代码

window.MyObject=function(){this.test=4;this.toString=function(){return"test object"}};

有什么方法可以使用Closure Compiler删除toString函数吗?

Is there any way I can remove the toString function using the Closure Compiler?

推荐答案

toString是隐式可调用的,因此,除非Closure编译器可以证明MyObject的结果从不强制转换为字符串,否则必须保留它.

toString is implicitly callable, so unless the Closure compiler can prove that the result of MyObject is never coerced to a string it has to preserve it.

您始终可以将其标记为显式调试代码:

You can always mark it as explicit debug code:

this.test = 4;
if (goog.DEBUG) {
  this.toString = function () { return "test object"; };
}

然后在您的非调试版本中进行编译

then in your non-debug build, compile with

goog.DEBUG = false;

请参见 http://closure-library.googlecode.com /svn/docs/closure_goog_base.js.source.html 可以

/**
 * @define {boolean} DEBUG is provided as a convenience so that debugging code
 * that should not be included in a production js_binary can be easily stripped
 * by specifying --define goog.DEBUG=false to the JSCompiler. For example, most
 * toString() methods should be declared inside an "if (goog.DEBUG)" conditional
 * because they are generally used for debugging purposes and it is difficult
 * for the JSCompiler to statically determine whether they are used.
 */
goog.DEBUG = true;

这篇关于Google Closure编译器高级:在编译时删除代码块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 16:59