我有以下构造函数和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
的属性。但是当你实例化SuperType
时,x
是该新对象的属性:
var y = new SuperType("foo");
console.log(x.isPrototypeOf(y)) // returns true
在你的例子中,SubType.prototype
是SuperType.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.
代替qazxsw poi,我们可以使用qazxsw poi,这将产生SubType.__proto__ = x
trik是Object.setPrototypeOf(SubType, x)
拥有原型的真实对象。 same result仅用于构造函数中,用于为构造对象定义原型。 (见__proto__
)
所以如果我们再次修改第一个例子
prototype