js 实现继承的方式有很多种,比如 原型链继承、借用构造函数继承、组合继承、寄生继承、寄生组合继承、ES6 新增的 extends 继承 ; 用的比较多的就是 原型链继承 还有 class 类函数继承
原型链继承
原型链继承涉及构造函数、原型和实例,三者之间存在着一定的关系,即每一个构造函数都有一个原型对象,原型对象又包含一个指向构造函数的指针,而实例则包含一个原型对象的指针。
//核心:将父类的实例作为子类的原型
function Guo() {
}
Guo.prototype = new Person(); //将Animal的实例挂载到了Dog的原型链上
//或:
//Guo.prototype = Object.create(Person.prototype)
Guo.prototype.name = 'dog';
var dog = new Guo();
console.log(dog.name); //dog
dog.eat('bone'); //dog正在吃:bone
dog.sleep(); //dog正在睡觉!
console.log(dog instanceof Person); //true
console.log(dog instanceof Guo); //true
class继承
class Person {
name;
age;
constructor(name, age) {
this.name = name
this.age = age
}
say() {
return `我在${this.age}干什么`
}
}
class Child extends Person {
run;
constructor(name,age, run) {
super(name,age)
this.run = run
}
// say() {
// return `我在干嘛${this.name}呢`
// }
st() {
return `${this.name}${this.age}岁,一事无成${this.run}`
}
}
let p = new Child('麻子', 22, '天天买醉')
console.log(p.st());
console.log(p);