How to check if a Javascript function is a constructor

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

    There is a quick and easy way of determining if function can be instantiated, without having to resort to try-catch statements (which can not be optimized by v8)

    function isConstructor(obj) {
      return !!obj.prototype && !!obj.prototype.constructor.name;
    }
    
    1. First we check if object is part of a prototype chain.
    2. Then we exclude anonymous functions

    There is a caveat, which is: functions named inside a definition will still incur a name property and thus pass this check, so caution is required when relying on tests for function constructors.

    In the following example, the function is not anonymous but in fact is called 'myFunc'. It's prototype can be extended as any JS class.

    let myFunc = function () {};
    

    :)

提交回复
热议问题