为什么foo.hasOwnProperty('__ proto__')等于false?

bat*_*man 6 javascript inheritance prototype

var foo = {
  bar : 5
}
Run Code Online (Sandbox Code Playgroud)

为什么foo.hasOwnProperty('__proto__')等于false

它不能从原型链中的任何对象升高,因为它特定于这个对象.

编辑:

一些答案说它已经开启了Object.prototype.

但我不明白这是多么合理.我的问题不是它的位置,而是为什么它不应该存在.

例如:

var a = new Foo();
var b = new Bar();
// Foo inherits from Bar
Run Code Online (Sandbox Code Playgroud)

所以不a.__proto__应该等于b.__proto__

既然他们都在读书Object.prototype

Ori*_*iol 5

实际上,__proto__是继承自Object.prototype:

foo.hasOwnProperty('__proto__')              // false
Object.prototype.hasOwnProperty('__proto__') // true
Run Code Online (Sandbox Code Playgroud)

根据MDN的文章,

这家酒店没什么特别的__proto__.它只是一个访问器属性 - 一个由getter函数和一个setter函数组成的属性 - 在Object.prototype上.

正如你所说的那样,直观地看起来,因为__proto__它本身与每个对象有关,所以它应该是一个自己的属性.

但它不是这样的.相反,Object.prototype.__proto__有一个getter函数,当调用不同的对象时,它会以不同的方式返回.

如果你跑,你可以获得类似的东西

Object.defineProperty(
    Object.prototype,
    'self',
    {get: function(){return this}}
)
Run Code Online (Sandbox Code Playgroud)

现在你可以调用.self不同的对象,你会得到不同的结果.

另请注意,此行为并不包括在内__proto__.例如,idHTML元素的属性也不是自己的属性:

var el = document.createElement('div');
el.id = 'foo';
el.hasOwnProperty('id');                // false
Element.prototype.hasOwnProperty('id'); // true
Run Code Online (Sandbox Code Playgroud)

(Webkit浏览器不符合规范,el.hasOwnProperty('id')true)