在 JavaScript 中,非标准属性 __ proto__ 和函数 Object.getPrototypeOf(...) 返回内部属性 [[Prototype]]。
对于所有函数,属性“prototype”都是 Object.prototype 的实例,例如:
Array.prototype instanceof Object//true
但 Object.prototype 却并非如此:
Object.prototype.__proto__ === null //true
Object.getPrototypeOf( Object.prototype ) === null //true
mozilla developer documentation只说:
An Object's proto property references the same object as its internal [[Prototype]] (often referred to as "the prototype"), which may be an object or, as in the default case of Object.prototype.proto, null .
Object.prototype.proto 更合适还是失败的 Object.getPrototypeOf (Object.prototype) 返回 Object.prototype 更合适?
这是一个错误吗?这个可以吗?为什么?
最佳答案
原型(prototype)链必须在某个地方停止。
如果 Object.getPrototypeOf( Object.prototype ) === Object.prototype
,JS 引擎在尝试解析原型(prototype)中的某些内容时将陷入无限循环。
它会沿着原型(prototype)链向上走到 Object.prototype
,如果在那里找不到它,它会再次向上走到 Object.prototype
,无限。
事实上,如果您尝试自己执行此操作,则会收到错误消息:
> Object.prototype.__proto__ = Object.prototype
Error: Cyclic __proto__ value
<小时/>
请注意,您还可以通过调用 Object.create(null)
创建自己的没有 [[Prototype]]
的对象。
关于javascript - 为什么 Object.prototype.__proto__ === null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18359062/