以下是我的
javascript代码
function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
function BController (){
}
function AController (){
BController.call(this);
}
AController.prototype.dosomething=function(){
}
如果我打电话
var g=new AController();
g.dosomething ();
一切都好.但如果我打电话(我希望AContronller继承BController)
extend(AController,BController);
var g=new AController();
g.dosomething ();
它总是报道
g.dosomething is not a function
方法2:
如果我改变Acontroller为
function AController ( ){
this.dosomethingNew=function(){
}
}
并打电话
extend(AController,BController);
var g=new AController();
g.dosomethingNew ();
没事的.
您的评论欢迎
最佳答案 你把这个电话扩展到了错误的地方.在调用扩展时,你将覆盖AController的整个原型,并在此过程中丢失dosomething.
相反,您需要在添加特定于AController的所有内容之前调用extend.
所以看起来应该是这样的:
function BController ( ){
} // <--- no semicolon after function declarations
function AController (){
BController.call(this);
} // <---- remove here too
extend(AController, BController); // <---- HERE
//Now AController's prototype is a new object whose prototype
//is BController's prototype, thereby inheriting everything from
//BController. Now you may add specific stuff to AController
AController.prototype.dosomething = function(){
};
这是一个functioning demo