最近我在看Babel.js (previously 6to5)。它是 ES6 的转译器。它提供的一项有趣的功能是将尾调用更改为循环。在示例中:
function factorial(n, acc = 1) {
"use strict";
if (n <= 1) return acc;
return factorial(n - 1, n * acc);
}
// Stack overflow in most implementations today,
// but safe on arbitrary inputs in eS6
factorial(100000)
Babel.js 将其转换为:
"use strict";
var _temporalAssertDefined = function (val, name, undef) { if (val === undef) { throw new ReferenceError(name + " is not defined - temporal dead zone"); } return true; };
var _temporalUndefined = {};
function factorial(_x2) {
var _arguments = arguments;
var _again = true;
_function: while (_again) {
var n = _temporalUndefined;
var acc = _temporalUndefined;
_again = false;
var n = _x2;
n = acc = undefined;
n = _arguments[0] === undefined ? undefined : _arguments[0];
acc = _arguments[1] === undefined ? 1 : _arguments[1];
"use strict";
if ((_temporalAssertDefined(n, "n", _temporalUndefined) && n) <= 1) {
return _temporalAssertDefined(acc, "acc", _temporalUndefined) && acc;
}_arguments = [_x2 = (_temporalAssertDefined(n, "n", _temporalUndefined) && n) - 1, (_temporalAssertDefined(n, "n", _temporalUndefined) && n) * (_temporalAssertDefined(acc, "acc", _temporalUndefined) && acc)];
_again = true;
continue _function;
}
}
// Stack overflow in most implementations today,
// but safe on arbitrary inputs in eS6
factorial(100000);
我的问题是,我从未见过像_function: while(again)
. 但它是有效的 JavaScript!我尝试a: 1
在 Chrome devtools 控制台中输入类似的代码,这是正确的。
谁能告诉我:
- 这个语法叫什么名字?
- 我在哪里可以获得语法信息?
- 在什么情况下我们需要写这样的代码?