在JavaScript中使用带有原型继承的InstanceOf

Using InstanceOf with Prototypal inheritance in JavaScript

本文关键字:原型 继承 InstanceOf JavaScript      更新时间:2023-11-03

我正在尝试使用原型继承,但遇到了麻烦。

不起作用

var Parent = function(){
}
var Child = function(){
    this.__proto__ = new Parent();
}
var child = new Child();
console.log(child instanceof Child) //logs false

但是是这样做的

var Parent = function(){
}
var Child = function(){
}
Child.prototype = new Parent();
var child = new Child();
console.log(child instanceof Child) // logs true

我想要第一个选项的唯一原因是这样我就可以利用父级的构造函数。我猜this是个问题,但我不太擅长javascript。我该如何做到这一点?

执行此操作的更好方法是call this:上的Parent构造函数

var Child = function(){
    Parent.call(this);
}

这样,Parent构造函数代码在Child构造函数中将其this设置为this的情况下运行,但不更改this__prototype__

您的两个示例确实生成了一个结构相同的child实例但是,主要区别在于在您的第一个示例Child.prototype != child.__proto__中。虽然Child.prototypechild.__proto__都是__proto__Parent.prototype的对象,但它们不是完全相同的对象,因此instanceof失败。

您可能还想执行Child.prototype = Object.create(Parent.prototype);,以便Child实例可以访问Parent的原型方法。(目前你在Parent.prototype上没有任何方法,但也许有一天你会的。)