JavaScript继承(设置内部原型)失败
我试图在构造函数中设置prototype属性,但它不起作用,但为什么?如果我将属性设置为外部,那么一切都可以正常工作。谢谢JavaScript继承(设置内部原型)失败,javascript,ecmascript-5,Javascript,Ecmascript 5,我试图在构造函数中设置prototype属性,但它不起作用,但为什么?如果我将属性设置为外部,那么一切都可以正常工作。谢谢 var a=function(){ this.x=1; } var b=function(){ this.prototype=new a(); this.getX=function(){ return this.x; } } alert(b.prototype); var test=new b(); alert(tes
var a=function(){
this.x=1;
}
var b=function(){
this.prototype=new a();
this.getX=function(){
return this.x;
}
}
alert(b.prototype);
var test=new b();
alert(test.getX());
发生的事情是,您正在为b的每个实例创建一个名为“prototype”的公共属性。不是要从中继承的实际原型对象
var a=function(){
this.x=1;
}
var b=function(){
this.getX=function(){
return this.x;
}
}
// every new instance of b will inherit 'x: 1'
b.prototype = new a();
console.log(b.prototype);
var test=new b();
console.log(test.getX());
查看此链接以了解有关的更多信息
好的,我想我已经明白了。因此prototype属性只与构造函数相关,而与实例无关。非常感谢。