在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)
replaceChild.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
,这将特别方便。