类的继承
如果两个类A和B,它们可以描述为:B是A,则A和B形成继承关系
如果B是A,则:
- B继承自A
- A派生B
- B是A的子类
- A是B的父类
如果A是B的父类,则B会自动拥有A中的所有实例成员。
在构造函数我们是怎么做的呢?
function Animal(type, name, age, sex) {
this.type = type;
this.name = name;
this.age = age;
this.sex = sex;
}
Animal.prototype.print = function() {
console.log(`【种类】:${this.type}`);
console.log(`【名字】:${this.name}`);
console.log(`【年龄】:${this.age}`);
console.log(`【性别】:${this.sex}`);
}
function Dog(name, age, sex) {
// 借用父类的构造函数
Animal.call(this, "犬类", name, age, sex);
}
const d = new Dog("旺财", 3, "公");
console.log(d);
这里用call改变了this指向 ,Dog类使用到了Animal类的方法。