有没有一种优雅的方式来区分 Harmony 的细长箭头函数与常规函数and内置函数?
The 和谐维基指出:
箭头函数就像内置函数一样缺乏原型以及任何 [[Construct]] 内部方法。所以 new (() => {}) 会抛出 TypeError 但除此之外箭头就像函数
这意味着,您可以测试箭头函数,例如:
!(()=>{}).hasOwnProperty("prototype") // true
!(function(){}).hasOwnProperty("prototype") // false
但测试也会回归true
对于任何内置函数,例如setTimeout
or Math.min
.
如果你获取源代码并检查它是否可以在 Firefox 中运行,它就可以了"native code"
,但它似乎不太可靠也不太可移植(其他浏览器实现,NodeJS / iojs):
setTimeout.toSource().indexOf("[native code]") > -1
小型 GitHub 项目节点是箭头函数依赖于正则表达式对函数源代码进行检查,这并不是那么简洁。
edit:我给了 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;