关闭编译器并没有将这个if语句压扁为" guard"使用&&

时间:2018-05-07 00:43:49

标签: javascript google-closure-compiler

我不明白为什么CC没有进一步编码。我经常用" guard"例如git fetch之类的陈述。但CC并没有将var x = obj.fun && obj.fun();缩减为"后卫"。

编译的js和预期的js实际上是不同的吗?

未编译的来源:

if

命令

window.test = function () {
  var ret = false;
  if (Math.random) {
    ret = Math.random() < 0.5;
  }
  return ret;
}

编译输出(美化):

npx google-closure-compiler \
--compilation_level ADVANCED \
--js test.js \
--js_output_file out.js

预期输出(&#34;我会做什么&#34;):

window.test = function() {
  var a = !1;
  Math.random && (a = 0.5 > Math.random());
  return a;
};

1 个答案:

答案 0 :(得分:1)

如果Math.random函数不存在,则此代码返回undefined

return Math.random && 0.5 > Math.random();

我认为返回false和返回undefined之间可能存在差异。