Is there an elegant way to tell Harmony's slim arrow functions apart from regular functions and built-in functions?
The Harmony wiki states that:
Arrow functions are like built-in functions in that both lack .prototype and any [[Construct]] internal method. So new (() => {}) throws a TypeError but otherwise arrows are like functions
Which means, you can test for arrow functions like:
!(()=>{}).hasOwnProperty("prototype") // true
!(function(){}).hasOwnProperty("prototype") // false
But the test will also return true
for any built-in function, e.g. setTimeout
or Math.min
.
It sort of works in Firefox if you get the source code and check if it's "native code"
, but it doesn't seem much reliable nor portable (other browser implementations, NodeJS / iojs):
setTimeout.toSource().indexOf("[native code]") > -1
The small GitHub project node-is-arrow-function relies on RegExp-checks against the function source code, which isn't that neat.
edit: I gave the JavaScript parser acorn a try and it seems to work quite okay - even though it's pretty overkill.
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;
this
to the function? Arrow functions are automatically bound to it, so there's no need for theself = this
hack or this-binding from outside. It might also be "better" to test for an arrow function instead of try/catchnew func
(equally applies to arrow and built-in functions). Either way, it feels like an oversight in the ECMAScript specs to not be able to reflect about these 3 different function types. – ArcheologyFunction.prototype.isGenerator
. – ArcheologysetTimeout
as for an arrow function. – Nicoliscallback
withthis
bound to something, I want to throw an error, ifcallback
is unboundable. – Historythis
and won't work the same way if they were arrow functions. – Bunkervar g = { f() { return 'x'; } }; g.f.hasOwnProperty('prototype') /* false */
– Hasheem