本文介绍了为什么foo.hasOwnProperty('__ proto__')等于false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var foo = {
  bar : 5
}

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

它不能来自原型链中的任何对象更高,因为它特定于这个对象。

It can't be from any object in the prototype chain higher up, because it is specific to this very object.

编辑

有些答案说它在 Object.prototype

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

But I don't understand how that makes sense. My question is not where it is, but why it isn't where it should be.

例如:

var a = new Foo();
var b = new Bar();
// Foo inherits from Bar

所以不应该 a .__ proto __ 等于 b .__ proto __

因为他们都在阅读off Object.prototype

Since they're both reading off Object.prototype ?

推荐答案

实际上, __ proto __ 继承自 Object.prototype

foo.hasOwnProperty('__proto__')              // false
Object.prototype.hasOwnProperty('__proto__') // true

根据,

As你说直觉看起来似乎是因为 __ proto __ 与每个对象有内在联系,它应该是一个属性。

As you say, intuitively it can seem that, since __proto__ is intrinsically related to each object, it should be an own property.

但它不是这样的。相反, Object.prototype .__ proto __ 有一个getter函数,当在不同的对象上调用时返回不同。

But it isn't like this. Instead, Object.prototype.__proto__ has a getter function which returns differently when called on different objects.

你可以如果你运行就得到类似的东西

You can obtain something similar if you run

Object.defineProperty(
    Object.prototype,
    'self',
    {get: function(){return this}}
)

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

Now you can call .self on different objects and you will get different results.

还要注意这个行为不是不包括 __ proto __ 。例如,HTML元素的 id 属性也不是自己的属性:

Also note this behavior isn't exclusive of __proto__. For example, the id property of an HTML element isn't an own property neither:

var el = document.createElement('div');
el.id = 'foo';
el.hasOwnProperty('id');                // false
Element.prototype.hasOwnProperty('id'); // true

这篇关于为什么foo.hasOwnProperty('__ proto__')等于false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 11:44