实现继承的方法有: class+extends 继承(ES6)
//类模板
class Animal {
constructor(name) {
this. name = name
}
}
//继承类
class Cat extends Animal { //重点。extends 方法,内部用 constructor+super
constructor(name) {
super(name);
//super作为函数调用时,代表父类的构造函数
} //constructor 可省略
eat () {
console. log("eating")
}
}
原型继承
//类模板
function Animal(name) {
this.name = name;
}
//添加原型方法
Animal. prototype. eat = function() {
console. log("eating")
}
function Cat(furColor) {
this. color = color;
};
//继承类
Cat. prototype = new Animal () //重点:子实例的原型等于父类的实例
借用构造函数继承
function Animal(name){
this.name = name
}
function Cat(){
Animal. call (this, "CatName")//重点,调用父类的 call 方法
}
寄生组合式继承(重点)
Was this helpful?
0 / 0