How to check if a Javascript function is a constructor

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

    As an addition to Felix Kling's answer, even if a function is not constructable, we can still use it like a constructor if it has a prototype property. We can do this with the help of Object.create(). Example:

    // The built-in object Symbol is not constructable, even though it has a "prototype" property:
    new Symbol
    // TypeError: Symbol is not a constructor.
    Object.create(Symbol.prototype);
    // Symbol {}
    //   description: (...)
    //   __proto__: Symbol
    

提交回复
热议问题