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

在JavaScript中使用带有原型继承的InstanceOf,javascript,inheritance,prototype,typechecking,Javascript,Inheritance,Prototype,Typechecking,我试图使用原型继承,但我遇到了麻烦 这不管用 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(){ }

我试图使用原型继承,但我遇到了麻烦

这不管用

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

我想要第一个选项的唯一原因是我可以利用父级的构造函数。我猜这就是问题所在,但我并不擅长javascript。如何使其工作?

更好的方法是调用
上的
父级
构造函数:

var Child = function(){
    Parent.call(this);
}
这样,
父级
构造函数运行时,其
this
设置为
子级
构造函数中的
this
,但您不会更改
this
原型

您的两个示例确实生成了一个结构相同的
实例。但是,主要区别在于,在第一个示例中,
Child.prototype!=child.\uuuu proto\uuuu
。虽然
Child.prototype
Child


您可能还需要执行
Child.prototype=Object.create(Parent.prototype)
这样子实例就可以访问父实例的原型方法。(目前你没有任何关于
Parent.prototype
的方法,但也许有一天你会的。)

当你说
这个时。

你说的是“好的,新对象,停止做
子对象,开始做
父对象。”因此,对象不再是子对象的实例也就不足为奇了。@apsillers是因为
这个
?为什么第二种方法不做同样的事情呢?是不是因为我在设定原型时不在
new Child
的范围内?啊,我现在理解你的困惑;我会更新我的答案。嗨,Josh,现在有点晚了,但也许下面的答案可以让你更好地理解prototype(共享成员)和
this
(实例成员):但这实际上是经典继承而不是原型继承。我完全想在父级或其原型上使用通用方法。我不需要设置
父级的结果。在子级上调用(this)
?并且,
Child.prototype=Object.create(Parent.prototype)
replace
Child.prototype=new Parent()?@JoshC。不,
Parent.call(this)
独立存在,因为它变异了
this
Parent
构造函数执行类似于
this.foo=5
的操作,因此在
Parent.call(this)
完成后,您的
this
具有
foo
属性。@JoshC。是的,您应该执行
Child.prototype=Object.create(Parent.prototype)
而不是
Child.prototype=new Parent()以下是一个原因示例:。基本上,
Parent
构造函数可能会对每个实例执行一些操作(比如设置一个唯一的ID),并且您不希望所有的
实例共享一个实例ID。@JoshC。是的,这就是问题所在。您还可以使用传入参数数组,如
Parent.apply(这是[arg1,arg2,arg3])
。如果您想通过执行
Parent.call(This,arguments)
Child
的所有参数传递给
Parent
,这将特别方便。