2
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @exclude_default_externs true
// @js_externs var console = {log: function(){}};
// @output_file_name default.js
// ==/ClosureCompiler==

/** @constructor */
function Test(){};
Test.prototype['action'] = function(){ 
  console.log('Hello');
  return this;
}

var test = new Test();

如果我添加该行:

test['action']()['action']()['action']();

并编译它我得到这个大小:

113 bytes (101 bytes gzipped)

如果我用这个等效代码替换该行:

test['action']();
test['action']();
test['action']();

我得到这个尺寸:

123 bytes (108 bytes gzipped)

我希望闭包编译器能够认识到,因为我的函数返回this,它可以将调用链接到action(它在第一次测试中是如何完成的)并获得更小的结果。有没有办法注释上面的代码,以便 Closure Compiler 能够进行这种优化?

注意:大小的差异是由链接引起的。输出的区别如下:

使用链接:

(new a).action().action().action();

没有链接:

var b=new a;b.action();b.action();b.action();
4

1 回答 1

1

有一个编译器通过:

https://code.google.com/p/closure-compiler/source/browse/src/com/google/javascript/jscomp/ChainCalls.java

但是,默认情况下未启用它。它没有为我们测试它的项目提供任何节省,但您可以尝试启用它。它由 Compiler 的 Java API 中的“CompilerOptions#setChainCalls”方法控制。

于 2013-06-10T05:31:00.227 回答