How to check if a Javascript function is a constructor

前端 未结 7 1679
名媛妹妹
名媛妹妹 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:29

    If the function is a constructor then it will have a "prototype" member which in turn has a "constructor" member that is equal to the function itself.

    function isConstructor(func) {
        return (func && typeof func === "function" && func.prototype && func.prototype.constructor) === func;
    }
    

提交回复
热议问题