Are functions objects or types in Javascript?

后端 未结 3 974
无人及你
无人及你 2021-02-07 05:38

In his Eloquent Javascript, Haverbeke claims that (page 16):

\"In a JavaScript system, most of this data is neatly separated into things called va

相关标签:
3条回答
  • They're a type of object.

    The typeof is "function":

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

    The internal [[Class]] is [object Function]:

    ({}).toString.call(function() {}) === "[object Function]" // true
    

    They're an instance of the Function constructor prototype:

    (function(){}) instanceof Function // true
    

    They're an instance of the Object constructor prototype:

    (function(){}) instanceof Object // true
    
    0 讨论(0)
  • 2021-02-07 05:53

    You need to be careful when talking about types in javascript. Values have a Type, which may be one of the following:

    1. Undefined
    2. Null
    3. Boolean
    4. String
    5. Number
    6. Object

    Perversely, the value returned by the typeof operator is not the Type, it's a string that is the same as the Type for most values, but is different for:

    1. Null returns 'object', even though its Type is Null
    2. An object that implements [[Call]] returns function, even though its Type is Object
    3. Host objects can return anything they like other than one of the restricted values

    So the bottom line is that the Type of a function is Object, but typeof someFn returns function.

    0 讨论(0)
  • 2021-02-07 06:02

    JavaScript supports functional programming. As a result all JavaScript functions are first-class functions, meaning that functions are treated like ordinary objects.

    http://en.wikipedia.org/wiki/First-class_functions

    0 讨论(0)
提交回复
热议问题