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(){ retur
How can I differentiate between these things in ES6?
.prototype
property. However, methods don't either. They inherit from Function.prototype
.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
..prototype
that is normally empty. They inherit from Function.prototype
..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.
You can't the first two cases get transpiled into this:
var x = function x(i) {
return i + 1;
};
function z(i) {
return i + 1;
}
For the last one you could check if it complains if it's a 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 that will obviously trigger the side effects of calling it, so it doesn't work in the general case.