Es5之前常用的三种继承
Es5继承
原型链继承
//原型链继承
//把父类的实力属性赋值给子类原型 , 就叫做原型链继承
//父类
function Fu(name) {
this.name = name
this.sleep = function () {
console.log(this.name + "会飞");
}
}
Fu.prototype.eat = function () {
console.log(this.name + "会跑");
}
//子类
function Zi() {
}
//子类继承父类
Zi.prototype = new Fu('小明')
let one = new Zi
one.sleep()
one.eat()
console.log(one.name);
构造函数继承
//父类
function Fu(name) {
this.name = name
this.sleep = function () {
console.log(this.name + "会飞");
}
}
Fu.prototype.eat = function(){
console.log(this.name+"会跑"); //
}
//子类
function Zi(name){
Fu.call(this,name)
}
let one = new Zi('构造函数继承')
console.log(one.name);
one.sleep()
//one.eat() // 报错 es5继承.html:102 Uncaught TypeError: one.eat is not a functionat
组合式继承
// 组合式继承
//原型链继承和构造函数继承的结合
//优点 : 可以传参 可以继承原型上的实例属性
// 父类
function Fu(name) {
this.name = name
this.sleep = function () {
console.log(this.name + "会飞");
}
}
Fu.prototype.eat = function () {
console.log(this.name + "会跑"); //
}
//子类
function Zi(name){
Fu.call(this,name)
}
Zi.prototype=new Fu()
//修改constructor指针
Zi.prototype.constructor=Zi
let one = new Zi('组合式继承')
console.log(one.name);
one.eat()
one.sleep()
Es6继承
class类
//es6的 class类 语法糖
class Fu {
constructor(name = "王", age = "18") {
this.name = name
this.age = age
}
eat() {
console.log(`${this.name} ${this.age} eat food`);
}
}
//继承父类
class Zi extends Fu {
constructor(name = "人", age = "20") {
//继承父类属性
super(name, age) //super指的是父亲的超集 people.call(this)
}
eat(){
//继承父类方法
super.eat()
}
}
let ZiObj = new Zi('嘻嘻嘻')
ZiObj.eat()
console.log(ZiObj.name);