【问题标题】:Why a property in an object is undefined, although it exists in object's __proto__?为什么对象中的属性未定义,尽管它存在于对象的 __proto__ 中?
【发布时间】:2017-05-31 03:25:51
【问题描述】:

首先,这是一个按预期工作的示例:

let a = { foo: 10 }
let b = { bar: 20 }
a.__proto__ = b

// returns value from prototype just fine
a.bar; // 20

这里有一个问题的例子,它不能按预期工作。为什么?

// "a" has no prototype when created this way
let a = Object.create(null);

// "b" has prototype and it is a JS native Object with a whole slew of its native props
let b = {};

// assign "a" a prototype
a.__proto__ = b;

// let's try
a.toString; // undefined

// but...
a.__proto__ .toString; // function toString() { [native code] }

为什么a.toString 会返回undefined,尽管已经分配了具有该属性的原型?

【问题讨论】:

  • a 仍然未定义,原型引用 b。所以 toString 应该返回 undefined

标签: javascript object prototypal-inheritance proto


【解决方案1】:

__proto__Object.prototype 的getter 和setter。

> Object.getOwnPropertyDescriptor(Object.prototype, '__proto__')
{ get: [Function: get __proto__],
  set: [Function: set __proto__],
  enumerable: false,
  configurable: true }

如果您创建的对象不是从 Object.prototype 继承的,则它没有该特殊属性,设置 __proto__ 将创建一个完全正常的属性。

这是 Object.prototype.__proto__ 的 setter 设置原型而不是创建属性:

> var a = {};
> a.__proto__ = { foo: 'bar' };
> Object.prototype.hasOwnProperty.call(a, '__proto__')
false

因为Object.prototype 不在链中,所以没有使用这个 setter:

> var b = Object.create(null);
> b.__proto__ = { foo: 'bar' };
> Object.prototype.hasOwnProperty.call(b, '__proto__')
true

改用Object.setPrototypeOf(总是):

Object.setPrototypeOf(a, b);

【讨论】:

    猜你喜欢
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 2021-11-10
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多