想写个类B继承A,将B.prototype写在function B外面没有任何问题 function A(){
this.Display();
}
A.prototype.Display=function(){alert("display!")};
A.prototype.constructor=A; var a=new A();
function B(){
this.Display();
}
B.prototype=a;
B.prototype.constructor=B; var b=new B();
现在我想写在function B的里面就出问题了 function A(){
this.Display();
}
A.prototype.Display=function(){alert("display!")};
A.prototype.constructor=A; var a=new A();
function B(){
B.prototype=a;
B.prototype.constructor=B;
this.Display();//这里老是报错:不支持方法Display
} var b=new B();为什么写到里面后A的成员都没有继承到B了?
this.Display();
}
A.prototype.Display=function(){alert("display!")};
A.prototype.constructor=A; var a=new A();
function B(){
this.Display();
}
B.prototype=a;
B.prototype.constructor=B; var b=new B();
现在我想写在function B的里面就出问题了 function A(){
this.Display();
}
A.prototype.Display=function(){alert("display!")};
A.prototype.constructor=A; var a=new A();
function B(){
B.prototype=a;
B.prototype.constructor=B;
this.Display();//这里老是报错:不支持方法Display
} var b=new B();为什么写到里面后A的成员都没有继承到B了?
即使你修改了B的prototype但b的prototype还是没有变
其次为什么不能将prototype写在函数里面,因为js在执行前会“预编译”函数和var变量,在预编译后才会产生prototype,而你将prototype写在函数里边,此时prototype还不存在,所以你这样写是有错的(我觉得),即使不出错,里面的数据也会丢失