构造函数继承

149 阅读1分钟

实现继承的方法:

  call方法
    在子类的构造函数中,调用父类的构造函数,并使用call方法修改函数中的this指向。
    call方法继承过来的属性都在子类身上。

  call问题:

    不能继承父类原型对象上的属性和方法。
    
父类
 function Animal(classes){
      this.classes = classes;
      this.speed = 10;
      this.hobby = "老鼠"
    }
    Animal.prototype.eat = function(){
      console.log("吃吃吃");
    }
    // var a1 = new Animal("猫");
    //    console.log(a1); //原型对象上有eat方法

    // 子类
    function Cat(age,color){
      this.age = age;
      this.color = color;
      Animal.call(this,"猫");
    }
    var c1 = new Cat(1,"blue");
    console.log(c1);//继承Animal的属性,但不能继承原型对象上的属性和方法,原型对象上没有eat方法