为什么isPrototypeOf()返回false?

问题描述 投票:8回答:3

我有以下构造函数和SubType原型指向SuperType的实例。当我做x.isPrototypeOf(SubType.prototype)它返回false。我很困惑,因为我明确地将x设置为SubType的原型。有人能告诉我为什么会这样吗?

function SuperType(){}
    
function SubType(){}

x = new SuperType();

SubType.prototype = x;
SubType.prototype.constructor = SubType;

console.log(x.isPrototypeOf(SubType)) // returns false
console.log(SuperType.prototype.isPrototypeOf(SubType.prototype)) // returns true
javascript
3个回答
7
投票

SubType是一个功能。您可能想要检查的是SubType的实例是否会从x继承:

function SuperType(){}
    
function SubType(){}

x = new SuperType();

SubType.prototype = x;
SubType.prototype.constructor = SubType;

const instance = new SubType();
console.log(x.isPrototypeOf(instance)) // returns true
console.log(SuperType.prototype.isPrototypeOf(SubType.prototype)) // returns true

3
投票

它有助于向对象添加属性以查看正在发生的事情。我修改了一些你的代码。您可以在控制台中运行它:

function SuperType(foo){ this.foo = foo };
function SubType(bar){ this.bar = bar };

var x = new SubType("bar");

SuperType.prototype = x;
SuperType.prototype.constructor = SubType;

现在,你问x.isPrototypeOf(SuperType)它返回false,因为x不是类SuperType的属性。但是当你实例化SuperType时,x是该新对象的属性:

var y = new SuperType("foo");
console.log(x.isPrototypeOf(y)) // returns true

在你的例子中,SubType.prototypeSuperType.prototype的原型并返回true。

console.log(SubType.prototype.isPrototypeOf(SuperType.prototype)) // returns true

0
投票

我认为这是对prototype__proto__属性的误解。

让我们稍微修改上面的例子

function SuperType(){}

function SubType(){}

x = new SuperType();

SubType.prototype = x;
console.log(x.isPrototypeOf(SubType)) // returns false.

// Now most interesting piece
SubType.__proto__ = x;
console.log(x.isPrototypeOf(SubType)) // Now true.

Demo

代替qazxsw poi,我们可以使用qazxsw poi,这将产生SubType.__proto__ = x

trik是Object.setPrototypeOf(SubType, x)拥有原型的真实对象。 same result仅用于构造函数中,用于为构造对象定义原型。 (见__proto__

所以如果我们再次修改第一个例子

prototype

here

© www.soinside.com 2019 - 2024. All rights reserved.