本文介绍了这怎么可能是真的??? obj2 .__ proto __.isPrototypeOf(obj2)//true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下简短代码:

let obj1 = {
  name: "obj1",
}

const obj2 = Object.create(obj1);
obj2.name = "obj2"

如果您console.log(obj2),它将在Google Chrome(版本79.0.3945.88(正式版本)(64位))中显示:

If you console.log(obj2), it will show this in Google Chrome (Version 79.0.3945.88 (Official Build) (64-bit)):

{name: "obj2"}
    name: "obj2"
    __proto__:
        name: "obj1"
        __proto__:
            constructor: ƒ Object()

或者,您最好查看此控制台屏幕截图图像:

Or, you better check this console screenshot image:

从Google Chrome浏览器显示的内容来看,显然obj2的第一个 proto 是obj1.这也是合乎逻辑的.怎么会这样呢?

From what Google Chrome presents, it is obvious that first proto of obj2 is obj1. It is logical too. How come then, that this is true:

obj2.__proto__.isPrototypeOf(obj2) // true

此外,这是怎么回事:

obj2.__proto__.__proto__.isPrototypeOf(obj1) // true

还有另一件事.如果JS中的普通对象没有原型属性(但是内部原型插槽不可访问),为什么.isPrototypeOf(obj2)未被定义?因为如果您这样做obj2.prototype,您就会得到.

And another thing. If ordinary object in JS, does not have prototype property (but internal prototype slot which is inaccessible), why .isPrototypeOf(obj2) is not undefined?? Because if you do obj2.prototype that's what you'll get.

我用谷歌搜索,但无济于事.

I googled and googled this but to no avail.

推荐答案

执行时

let obj1 = {
  name: "obj1",
}

const obj2 = Object.create(obj1);

您正在使用以下原型链创建obj2:

You're creating an obj2 with the following prototype chain:

Object.prototype -> obj1 -> obj2

(Object.protoypeobj1都在obj2的内部原型链之内)

(Both Object.protoype and obj1 are within obj2's internal prototype chain)

当引用对象的__proto__属性时,这将指向当前对象的内部原型.因此,例如obj2.__proto__obj1.

When you reference the __proto__ property on an object, this will point you to the internal prototype of the current object. So, for example, obj2.__proto__ is obj1.

(尽管已弃用.__proto__,但它不是不可访问)

(Although .__proto__ is deprecated, it's not inaccessible)

所以

obj2.__proto__.isPrototypeOf(obj2) // true

等同于

obj1.isPrototypeOf(obj2) // true

obj1 确实在obj2的内部原型链中,因此其评估结果为true.

And obj1 is indeed within obj2's internal prototype chain, so it evaluates to true.

类似地,

obj2.__proto__.__proto__.isPrototypeOf(obj1) // true

这是

obj2.__proto__.__proto__.isPrototypeOf(obj1) // true
          obj1.__proto__.isPrototypeOf(obj1) // true
        Object.prototype.isPrototypeOf(obj1) // true

这也很有意义-Object.prototype确实在obj1的原型链之内.

Which makes sense as well - Object.prototype is indeed within obj1's prototype chain.

最好使用未弃用的版本Object.getPrototypeOf而不是__proto__,它们会做同样的事情:

It's better to use the non-deprecated version Object.getPrototypeOf instead of __proto__, they do the same thing:

let obj1 = {
  name: "obj1",
};
const obj2 = Object.create(obj1);

console.log(obj2.__proto__ === obj1);
console.log(Object.getPrototypeOf(obj2) === obj1);

这篇关于这怎么可能是真的??? obj2 .__ proto __.isPrototypeOf(obj2)//true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 05:29