I noticed not all the Javascript functions are constructors.
var obj = Function.prototype;
console.log(typeof obj === \'function\'); //true
obj(); //OK
new
With ES6+ Proxies, one can test for [[Construct]]
without actually invoking the constructor. Here's a snippet:
const handler={construct(){return handler}} //Must return ANY object, so reuse one
const isConstructor=x=>{
try{
return !!(new (new Proxy(x,handler))())
}catch(e){
return false
}
}
If the passed item isn't an object, the Proxy
constructor throws an error. If it's not a constructable object, then new
throws an error. But if it's a constructable object, then it returns the handler
object without invoking its constructor, which is then not-notted into true
.
As you might expect, Symbol
is still considered a constructor. That's because it is, and the implementation merely throws an error when [[Construct]]
is invoked. This could be the case on ANY user-defined function that throws an error when new.target
exists, so it doesn't seem right to specifically weed it out as an additional check, but feel free to do so if you find that to be helpful.