SOURCE

function Animal (age) {
    this.name = "动物"
    this.age = age
    this.type = "Animal 类"
    this.sleep = function () {
      console.log(this.name +'正在睡觉!')
    }
}

Animal.prototype.eat = function (food) {
    console.log(this.name +'正在吃:'+ food);
}

// 子类

function Cat (name, age) {
    // 核心,通过call()函数实现Animal的实例的属性和函数的继承
   Animal.call(this, age)
   this.name = name || 'Tom'
}

// 子类的实例

const cat = new Cat('tony', 3)

console.log(cat.name) // tony
console.log(cat.type) // Animal 类
cat.sleep() // tony正在睡觉!
console.log(cat.age) // 3 , 创建子类的实例时,可以向父类传递参数
// cat.eat('火腿肠') // TypeError: cat.eat is not a function

/* 

构造继承的优点:

1.可解决子类实例共享父类属性的问题

call()函数实际是改变了父类Animal构造函数中this的指向,调用后this指向了子类Cat,相当于将父类的type、age和sleep等属性和函数直接绑定到了子类的this中,成了子类实例的属性和函数,因此生成的子类实例中是各自拥有自己的type、age和sleep属性和函数,不会相互影响。

2.创建子类的实例时,可以向父类传递参数

3.可以实现多继承


构造继承的却缺点:

1.实例只是子类的实例,并不是父类的实例

2.只能继承父类实例的属性和函数,并不能继承原型对象上的属性和函数

3.无法复用父类的实例函数

*/
console 命令行工具 X clear

                    
>
console