`
阅读更多
  1. 通过继承子类将拥有父类的所有属性和方法,以下举例3中继承方式,原型继承、借用构造方法继承、组合继承(原型 + 借用构造方法)
  2. 原型链继承(子类的原型指向父类对象)
    function Father(){
      this.type = "father";
      this.money = [];
    }
    Father.prototype.getType = function(){
      return this.type
    }


    function Son(){
      
    }
    Son.prototype = new Father();//无法给父类传参
    var son = new Son();
    son.money.push(1);
    var son1 = new Son();
    son1.money;//1
    //弊端:无法给父类传参;最严重的是所有子类实例将共享父类属性,这对于引用属性影响是很大的,如上更改了son的money属性,也影响了son1money属性
  3. 借用构造函数继承(即在子类中调用父类的构造函数)
    function Father(type){
      this.type = type;
    }
    Father.prototype.getType = function(){
      return this.type
    }


    function Son(type){
      Father.call(this,type);//调用父类的构造方法
    }
    var son = new Son("son");
    son.type;//output son
    son.getType();//error
    特点:解决了原型继承无法传参问题                                                                                                    问题:借用构造方法方式也有问题就是父类的原型方法子类是不可见的,函数复用无从谈起
  4. 组合继承,结合了原型继承和借用构造方法继承有点,成为了最常用的继承方式
    function Father(type){
      this.type = type;
      this.money = [];
    }
    Father.prototype.getType = function(){
      return this.type
    }


    function Son(type){
      Father.call(this,type);//借用构造方法继承
    }
    Son.prototype = new Father();//原型继承
    var son = new Son("son");
    son.getType();//output son 解决借用构造继承,原型方法不可见问题

    var son1 = new Son();
    son.money.push(1);
    son1.money;//output [] 解决原型继承对引用类型的类属性的影响     
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics