Is Function really an Object

后端 未结 5 620
不思量自难忘°
不思量自难忘° 2020-12-07 04:15

I am a self taught web developer and am still trying to come to grips with some JavaScript fundamentals. Below are some quotes extracted from Douglas Crockford\'s Good Part

5条回答
  •  一生所求
    2020-12-07 04:23

    If Function is an Object then why is its type a function and not object?

    Because the typeof operator is defined like that, probably for usability:

    • Object (native and does not implement [[Call]]) returns "object"
    • Object (native or host and does implement [[Call]]) returns "function"
    • Object (host and does not implement [[Call]]) returns an Implementation-defined value that may not be "undefined", "boolean", "number", or "string".

    [[Call]] is an internal property of an object that identifies the object as a function (callable). A non-native object is an object provided by the host (e.g. browser), such as a DOM object or an instance of ActiveXObject.

    puzzled so the constructor is in-fact a function?

    Why wouldn't it be? Constructors are functions. Instances can only be constructed using functions. Object.constructor is a function, but it's also an object. See the following:

    console.log((function () { }) instanceof Object);
    //-> true
    

    Also, from the ECMAScript speficiation:

    Every built-in function and every built-in constructor has the Function prototype object, which is the initial value of the expression Function.prototype (15.3.4), as the value of its [[Prototype]] internal property.

    Unless otherwise specified every built-in prototype object has the Object prototype object, which is the initial value of the expression Object.prototype (15.2.4), as the value of its [[Prototype]] internal property, except the Object prototype object itself.

    And also, to answer your final puzzlement:

    The Function prototype object is itself a Function object (its [[Class]] is "Function") that, when invoked, accepts any arguments and returns undefined.

提交回复
热议问题