繁体   English   中英

为什么isPrototypeOf()返回false?

[英]Why does isPrototypeOf() return false?

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

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 

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

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类的属性。 但是当您实例化SuperTypex是该新对象的属性:

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

我认为这是对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.

演示

代替SubType.__proto__ = x我们可以使用Object.setPrototypeOf(SubType, x) ,这将产生相同的结果

trik是__proto__包含真实对象,它是原型。 prototype仅在构造函数中用于定义构造对象的原型。 (见这里

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

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

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM