在检查浏览器是否支持spread,然后加载适当的脚本时
可能的
,有一个更简单的选择:将Babel这样的工具集成到构建过程中,以自动将ES6+语法的代码传输到ES5。例如,如果您将以下内容插入
Babel
:
function debug (mode, string, ...params) {
if (debug_enabled && window.console) {
console.log(mode+": "+string+"(",...params,");");
}
}
你得到
"use strict";
function debug(mode, string) {
if (debug_enabled && window.console) {
var _console;
for (var _len = arguments.length, params = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
params[_key - 2] = arguments[_key];
}
(_console = console).log.apply(_console, [mode + ": " + string + "("].concat(params, [");"]));
}
}
你可以试一试
here
.
这允许您使用最新、最好的语言版本编写、读取和调试,同时仍然允许过时的浏览器理解脚本的语法。
当然,Babel不仅仅限于传输扩展语法,它还可以传输
全部的
从现代语法一直到ES5(如解构、对象扩展、求幂)(
**
),以及更多)。
尽管如此,请注意
语法
和新的不同
内置函数
例如
Array.prototype.includes
是ES6的一个特性,但因为它是一个新函数,而不是新语法,所以它不会被传输——为了让旧浏览器也能理解新函数,可以使用polyfills,例如,
polyfill.io
.
如果您真的希望能够动态确定当前客户端是否支持扩展语法,可以使用
new Function
要查看语法分析是否正确,请执行以下操作:
function supportsSpread() {
try {
new Function('foo(...params);');
return true;
} catch(e) {
return false;
}
}
console.log(supportsSpread());
(但真的没有什么好的理由这么做)