除了常规功能和内置功能之外,还有一种优雅的方式可以告诉Harmony的纤细箭头功能吗?
在和谐维基指出:
箭头函数就像内置函数一样缺乏.prototype和任何[[Construct]]内部方法.所以new(()=> {})抛出一个TypeError,否则箭头就像函数一样
这意味着,您可以测试箭头功能,如:
!(()=>{}).hasOwnProperty("prototype") // true
!(function(){}).hasOwnProperty("prototype") // false
Run Code Online (Sandbox Code Playgroud)
但是测试也将返回true
任何内置函数,例如setTimeout
或Math.min
.
如果您获得源代码并检查它是否可以在Firefox中运行"native code"
,但它看起来不太可靠也不可移植(其他浏览器实现,NodeJS/iojs):
setTimeout.toSource().indexOf("[native code]") > -1
Run Code Online (Sandbox Code Playgroud)
小的GitHub项目node-is-arrow-function依赖于函数源代码的RegExp检查,这不是那么整洁.
编辑:我尝试了一下JavaScript解析器橡子,看起来工作得很好 - 即使它太过分了.
acorn = require("./acorn");
function fn_sample(a,b){
c = (d,e) => d-e;
f = c(--a, b) * (b, a);
return f;
}
function test(fn){
fn = fn || fn_sample;
try {
acorn.parse("(" + fn.toString() + ")", {
ecmaVersion: 6,
onToken: function(token){ …
Run Code Online (Sandbox Code Playgroud) javascript function ecmascript-harmony ecmascript-6 arrow-functions