How can I distinguish between arrow function, class and normal function?

How can I distinguish between these three things in ES6 using its link?

let x = i => i+1; class y { constructor(i) { this._i=i+1; } get i(){ return this._i;} } function z(i) { return i+1; } 

Example:

 test(x) //=> 'arrow' test(y) //=> 'class' test(z) //=> 'function' 

And how can I distinguish these things in transpilers - Traceur / Babel?

+4
javascript ecmascript-6 arrow-functions
source share
2 answers

How can I distinguish between these things in ES6?

  • Arrow functions are functions that cannot be used as constructors and do not have the .prototype property. However, methods do not exist either. They inherit from Function.prototype . Classes
  • are functions that cannot be called without new , and which have a .prototype object, which is usually not empty. If the extends keyword was used, they are not inherited from Function.prototype .
  • functions are functions that can be called anyway and have .prototype usually empty . They inherit from Function.prototype .
  • Generator functions are functions that have a .prototype that inherits from an internal GeneratorPrototype object and inherits from an internal Generator object.

As you can see, there are some tips. However, properties and inheritance can always be confusing, so you cannot trust it. Whether a function is a constructor (can be called using new ) cannot be defined externally, you must call it and see if it is thrown - which can also be faked.

So your best bet might be Function.prototype.toString to see what the source looks like. If your ES implementation supports this.

And how can I distinguish between these things in transpilers?

I do not think that any transporter implements arrows and methods that do not contain prototypes. Whether the class constructor is created upon invocation depends on the weakness of the transpilation, but in any case this is not the best way to distinguish it.
toString does not work either afaik.

+7
source share

You cannot transfer the first two cases:

 var x = function x(i) { return i + 1; }; function z(i) { return i + 1; } 

In the latter case, you can check if it complains to the class when you call it:

 function isClass(instance){ try{ instance() }catch(e){ return e.message === "Cannot call a class as a function"; } return false; } 

But this, obviously, will cause side effects of its call, so in the general case this will not work.

+1
source share

All Articles