实际上,__proto__
继承自Object.prototype
:
foo.hasOwnProperty('__proto__') // false
Object.prototype.hasOwnProperty('__proto__') // true
并根据MDN 文章 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto#Description,
没有什么特别之处__proto__
财产。这简直就是
访问器属性——由 getter 函数和
setter 函数 -- on对象.原型 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype.
正如你所说,直觉上似乎是这样,因为__proto__
与每个对象本质上相关,它应该是一个自己的属性。
但事实并非如此。反而,Object.prototype.__proto__
有一个 getter 函数,在不同的对象上调用时返回不同的结果。
如果你运行你可以获得类似的东西
Object.defineProperty(
Object.prototype,
'self',
{get: function(){return this}}
)
现在你可以打电话.self
在不同的物体上,你会得到不同的结果。
另请注意,此行为并不排除__proto__
。例如,id
HTML 元素的属性也不是自己的属性:
var el = document.createElement('div');
el.id = 'foo';
el.hasOwnProperty('id'); // false
Element.prototype.hasOwnProperty('id'); // true
(Webkit browsers don't follow the spec and el.hasOwnProperty('id')
is true
)