JS prototype 继承

最简单的原型继承方法:      

 function  A(name){

this.name=name;

};


//假设A有一个方法getName
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


猜你喜欢

转载自blog.csdn.net/qq_35319282/article/details/73604453