Google Closure Compiler advanced: remove code blocks at compile time

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

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

I get this code

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

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


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;

See which does

 * @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;