Correct prototype chain for Function

前端 未结 4 983
-上瘾入骨i
-上瘾入骨i 2020-12-05 03:38

What is the correct output (meaning correct by the ECMA standard) of the following program?

function nl(x) { document.write(x + \"
\"); } nl(Functio
4条回答
  •  北海茫月
    2020-12-05 04:00

    Function.prototype

    From ECMAScript Language Specification:

    15.3.3.1 Function.prototype

    The initial value of Function.prototype is the Function prototype object (section 15.3.4).

    15.3.4 Properties of the Function Prototype Object

    The Function prototype object is itself a Function object (its [[Class]] is "Function") that, when invoked, accepts any arguments and returns undefined. The value of the internal [[Prototype]] property of the Function prototype object is the Object prototype object (section 15.3.2.1).

    It is a function with an “empty body”; if it is invoked, it merely returns undefined. The Function prototype object does not have a valueOf property of its own; however, it inherits the valueOf property from the Object prototype Object.

    I get this output:

    • Opera: function () { [native code] }
    • Chrome: function Empty() {}
    • IE7: function prototype() { [native code]}
    • FF3: function () { }

    Chrome and IE7 has named their functions, Opera and IE7 tells you that it will not reveal the implementation. They all agree on this:

    nl(typeof Function.prototype); //function
    

    Compare this to:

    nl(typeof Object.prototype); //object
    nl(typeof Array.prototype); //object
    nl(typeof String.prototype); // object
    

    Function.prototype.prototype

    I get undefined from Opera and IE7, null from Chrome and [object Object] from FF3. Who is right? Since "The Function prototype object is itself a Function object" shouldn't it be a circular reference to itself? To avoid the circular reference they have chosen different ways. I don't know if there is a standard for that or if it is up to the implementation, but I think an Object is right. Btw, here you see the difference between the internal [[prototype]] and the public prototype in action, like you asked in an earlier question!

    Function.prototype.prototype == Object.prototype

    This is false because it isn't the same object. See above.

    Function.prototype.prototype.prototype

    Only FF will give you an answer because of their implementation of Function.prototype.prototype returns an Object.

    I agree that your proposed output looks more logic.

    They do agree on this:

    nl(Object.prototype); // [object Object]
    nl(Object.prototype.prototype); // undefined
    

提交回复
热议问题