最简单的原型继承方法:
function A(name){
};
A.prototype.getName=function(){
return this.name;
}
function B(name){
this.name=name;
}
//想让B方法也有A的getName方法只需要:
B.prototype=new A();//等同于下面2行
//var temp = new A("A"); //B.prototype = temp;
B.prototype.constructor=B; //让B的constructor指向自己,方便管理
调用:
var b=new B("abc");
b.getName();//abc
然后可以自己封装一个继承的方法 extend,想让那个类继承那个类直接extend(B,A);
function extend(superClass,childClass){
debugger
var temp = new superClass();
childClass.prototype = temp;
childClass.prototype.constructor=childClass;
}
调用:
var b=new B("abc");
b.getName();//abc