为什么isPrototypeOf()返回false?

时间:2019-04-24 01:56:33

标签: javascript

我有下面的构造函数和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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

我们可以使用SubType.__proto__ = x代替Object.setPrototypeOf(SubType, x),它会产生same result

trik是__proto__,它持有作为原型的真实对象。 prototype仅在构造函数中用于定义构造对象的原型。 (请参见here

因此,如果我们再次修改第一个示例

function SuperType(){}

function SubType(){}

x = new SuperType();

SubType.prototype = x;

console.log(x.isPrototypeOf(SubType)) // returns false

var x2 = new SubType();
console.log(x.isPrototypeOf(x2)) // returns true

Demo

相关问题