How to check if a Javascript function is a constructor

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

    For question 1, what about this helper?

    Function.isConstructor = ({ prototype }) => Boolean(prototype) && Boolean(prototype.constructor)
    
    Function.isConstructor(class {}); // true
    Function.isConstructor(function() {}); // true
    Function.isConstructor(() => {}); // false
    Function.isConstructor("a string"); // false
    

    For question 2, the arrow function is the solution. It cannot be used as a constructor since it does not rely on the same scope as a regular function and does not have a prototype (definition of instances, similar to class definition for real OOP)

    const constructable = function() { console.log(this); };
    const callable = () => { console.log(this); };
    
    constructable(); // Window {}
    callable(); // Window {}
    new constructable(); // aConstructableFunction {}
    new callable(); // Uncaught TypeError: callable is not a constructor
    

提交回复
热议问题