除了常规函数和内置函数之外,有没有一种优雅的方式来区分 Harmony 的细长箭头函数?
在和谐维基指出:
箭头函数就像内置函数一样,都缺少 .prototype和任何 [[Construct]] 内部方法。所以 new (() => {}) 抛出一个 TypeError 但否则箭头就像函数
这意味着,您可以测试箭头函数,例如:
!(()=>{}).hasOwnProperty("prototype") // true
!(function(){}).hasOwnProperty("prototype") // false
但是测试也将返回true任何内置函数,例如setTimeoutor Math.min。
如果您获取源代码并检查它是否在 Firefox 中,它可以在 Firefox 中工作"native code",但它似乎不太可靠或可移植(其他浏览器实现,NodeJS / iojs):
setTimeout.toSource().indexOf("[native code]") > -1
GitHub 小项目node-is-arrow-function依赖于针对函数源代码的 RegExp 检查,这不是那么整洁。
编辑:我尝试了 JavaScript 解析器acorn,它似乎工作得很好 - 即使它非常矫枉过正。
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){
                if(typeof token.type == "object" && token.type.type == "=>"){
                    console.log("ArrowFunction found", token);
                }
            }
        });
    } catch(e) {
        console.log("Error, possibly caused by [native code]");
        console.log(e.message);
    }
}
exports.test = test;