Why is foo.hasOwnProperty('__proto__') equal to false?

后端 未结 1 2197
天涯浪人
天涯浪人 2021-02-15 17:00
var foo = {
  bar : 5
}

Why is foo.hasOwnProperty(\'__proto__\') equal to false?

It can\'t be from any object in the

相关标签:
1条回答
  • 2021-02-15 17:35

    In fact, __proto__ is inherited from Object.prototype:

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

    And according to MDN article,

    There is nothing special about the __proto__ property. It is simply an accessor property -- a property consisting of a getter function and a setter function -- on Object.prototype.

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

    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}}
    )
    

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

    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
    

    (Webkit browsers don't follow the spec and el.hasOwnProperty('id') is true)

    0 讨论(0)
提交回复
热议问题