Why use typeof for identifying a function?

后端 未结 6 607
天涯浪人
天涯浪人 2020-12-09 13:03

Are there any significant reasons for using

typeof variable === \'function\'

versus

!!variable.call

for d

6条回答
  •  不思量自难忘°
    2020-12-09 13:28

    The safest way is to check the internal [[Class]] property by setting the object as the thisArg argument of the .call() method when calling Object.prototype.toString.

    Object.prototype.toString.call( myVariable ) === '[object Function]';
    

    Of course you could easily make a function out of it:

    function checkClass( obj ) {
        return Object.prototype.toString.call( obj ).slice( 8, -1).toLowerCase();
    }
    
    checkClass( myVariable ) === 'function';
    

    This is very simple, and there could be some improvements, but you get the idea.

提交回复
热议问题