Why use typeof for identifying a function?

后端 未结 6 603
天涯浪人
天涯浪人 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:36

    According to the ECMAScript specification, the following should apply for regular expression literals:

    A regular expression literal is an input element that is converted to a RegExp object (section 15.10) when it is scanned. The object is created before evaluation of the containing program or function begins.

    So typeof /regex/ should yield "object":

    typeof /regex/ === "object"
    

    And the constructor of the object created by the regular expression literal should be RegExp:

    /regex/.constructor === RegExp
    

    Similar to that, a function definition should yield a Function object:

    (function(){}).constructor === Function
    

    But although this returns a Function object, the typeof operator should not yield "object" but "function" instead:

    typeof function(){} === "function"
    

    This is due to the distinction whether the object implements the internal [[Call]] property that is special for Function objects.

    Note that all this is how Javascript implementations should behave. So all equations are asserted to be true.

提交回复
热议问题