Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

javascript - How can I differentiate between an arrow function, class and a normal function?

How can I differentiate between these three things in ES6 using its reference?

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 differentiate between these things in transpilers - Traceur / Babel?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How can I differentiate between these things in ES6?

  • arrow functions are functions that cannot be used as constructors, and don't have a .prototype property. However, methods don't either. They inherit from Function.prototype.
  • classes are functions that can't be called without new, and that have a .prototype object which is normally not empty. If the extends keyword was used, they don't inherit from Function.prototype.
  • functions are functions that can be called either way, and do have a .prototype that is normally empty. They inherit from Function.prototype.
  • generator functions are functions that do have a .prototype which inherits from the intrinsic GeneratorPrototype object, and they inherit from the intrinsic Generator object.

As you can see, there are some clues. However, the properties and inheritance can always be messed with, so you cannot really trust it. Whether a function is a constructor (can be called with new) cannot be determined from outside, you have to call it and see whether it throws - which could be faked as well.

So your best bet might be Function.prototype.toString, to see how the source looked like. If your ES implementation supports that.

And how can I differentiate between these things in transpilers?

I don't think any transpiler implements prototype-less arrows and methods. Whether a class constructor throws upon being called depends on the looseness of the transpilation, but that's not a good way for distinction anyway.
toString doesn't work either afaik.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...