正确的函数原型链 [英] Correct prototype chain for Function

查看:30
本文介绍了正确的函数原型链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下程序的正确输出是什么(ECMA 标准的意思是正确的)?

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

function nl(x) { document.write(x + "<br>"); }
nl(Function.prototype);
nl(Function.prototype.prototype);
nl(Function.prototype.prototype == Object.prototype);
nl(Function.prototype.prototype.prototype);

Chrome 和 IE6 一致认为:

Chrome and IE6 agree in saying:

function Empty() {}
null for Chrome / undefined for IE6
false

然后崩溃.

Mozilla 输出:

Mozilla outputs:

function () { }
[object Object]
false
undefined

这两个是否正确?似乎 Mozilla 的一个做得更好,但最好的输出是

Are either of these correct? It seems that the Mozilla one does better, but that the best output is

function () { }
[object Object]
true
undefined

推荐答案

你在这里所做的并不是真正走原型链 - 这个问题 可能会帮助您了解实际发生的情况.我没有费心去检查 ECMA 规范,但这是我对这个问题的看法:

What you're doing here isn't really walking the prototype chain - this question might help you understand what is actually going on. I didn't bother to check the ECMA spec, but here is my take on the issue:

  • Function是函数对象的构造器

Function.prototype 是所有函数对象继承的原型 - 它可能包含像 callapply 这样的属性所有Function 实例通用;您检查的实现是一致的,因为它本身是作为函数对象实现的(正如某些指出的那样,ECMA 规范要求这样做)

Function.prototype is the prototype from which all function objects inherit - it might contain properties like call and apply which are common to all Function instances; the implementations you checked were consistent in that it is implemented as a function object itself (as some pointed out, the ECMA specification requires this)

Function.prototype.prototype 并没有多大意义,但由于 Function.prototype 被实现为一个函数对象(可能会被使用)作为构造函数),它至少应该存在;使用 Function.prototype 作为构造函数创建的对象将继承其属性 - 但因为没有理由做这样疯狂的事情,将其设置为 null, undefined 或者一个空对象是合理的

Function.prototype.prototype does't really make much sense, but as Function.prototype is implemented as a function object (which could possibly be used as a constructor), it should at least exists; objects which are created using Function.prototype as constructor would inherit its properties - but as there should be no reason to do something insane like this, setting it to null, undefined or an empty object is reasonable

Function.prototype.prototype.prototype 很可能未定义:正如我们之前看到的,Function.prototype.prototype 应该是没有属性的(nullundefined 或空对象)并且绝对不是函数对象;因此,它的 prototype 属性应该是 undefined 或者甚至可能在尝试访问时抛出错误

Function.prototype.prototype.prototype will in all likelyhood be undefined: as we have seen before, Function.prototype.prototype should be something without properties (null, undefined or an empty object) and definetely not a function object; therefore, its prototype property should be undefined or might even throw an error when trying to be accessed

希望这有帮助;)

这篇关于正确的函数原型链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆