gpt4 book ai didi

javascript - 改变对象原型(prototype)

转载 作者:行者123 更新时间:2023-12-03 02:55:05 24 4
gpt4 key购买 nike

我有以下两个功能:

function Dog() {}
function Cat() {}

我设置了Dog.prototype = new Cat()

然后我创建一个 dog 实例:

let dog = new Dog();

为什么dog instanceof Dog === true。我明白为什么 dog instanceof Cat === true 因为我只是将它设置为 Catprototype 但仍然有一些对 的引用code>Dog prototype 甚至在创建实例之前就已被覆盖?我如何使dog instanceof Dog === false

最佳答案

正如 MDN 文档中提到的

The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.

这意味着 instanceof 将使用 Object__proto__ 检查构造函数的 prototype 属性,而不是prototype 所持有的值。您可以按如下方式检查

console.log(Dog.prototype === dog.__proto__) // prints -> true
console.log(Dog.prototype === Object.getPrototypeOf(dog)) // prints -> true

您所做的只是更改原型(prototype)的 `值。它仍然是相同的属性。

修改:

看看 instanceof 方法的简化实现

function instanceOf(object, constructor) {
return Object.getPrototypeOf(object) === constructor.prototype;
}

在这里,您可以看到,如果 Object.getPrototypeOf(object) 的引用等于 constructor,则 instanceof 返回 true .prototype。在您的情况下,Dog.prototypeCat,而Object.getPrototypeOf(dog) 也是Cat。这就是为什么 instanceof 将始终返回 true。

引用

链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof

搜索Object.getPrototypeOf(o) === C.prototype

关于javascript - 改变对象原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47667121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com