How to check if a Javascript function is a constructor

前端 未结 7 1663
名媛妹妹
名媛妹妹 2020-12-05 00:08

I noticed not all the Javascript functions are constructors.

var obj = Function.prototype;
console.log(typeof obj === \'function\'); //true
obj(); //OK
new          


        
相关标签:
7条回答
  • 2020-12-05 00:30

    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.

    0 讨论(0)
提交回复
热议问题