继承分为es5和es6继承
es5继承常用的继承
原型链继承
function Father() {
this.name = '父'
this.age = [1, 2, 3, 4]
}
Father.prototype.getName = function () {
return this.name
}
function Child() {
this.child = '子'
}
Child.prototype = new Father()
let child1 = new Child()
let child2 = new Child()
child1.age.push(5)
console.log(child1.age, child2.age);//child1.age === child2.age
//因为这两个实例使用同一个原型对象,所以共享同一块内存地址
console.log(child1.getName()) // '父'
构造函数
function Father() {
this.name = '父'
this.age = [1, 2, 3, 4]
}
Father.prototype.getName = function () {
return this.name
}
function Child() {
Father.apply(this)
this.child = '子'
}
let child1 = new Child()
let child2 = new Child()
child1.age.push(5)
console.log(child1.age, child2.age); //两个实例互不影响
//相比第一种(原型链继承)做了优化,但也有弊端,只能继承父的实例属性和方法,继承不到父的原型属性和方法
console.log(child1.getName());//会报错 拿不到
组合继承
function Father() {
this.name = '父'
this.age = [1, 2, 3, 4]
}
Father.prototype.getName = function () {
return this.name
}
function Child() {
Father.apply(this)
this.child = '子'
}
Child.prototype = new Father()
//Child.prototype.constructor = Child
let child1 = new Child()
let child2 = new Child()
child1.age.push(5)
console.log(child1.age, child2.age);
console.log(child1.getName());
es6使用class继承
class类
class father {
constructor(name,age){ //父的构造函数
this.name = name //父的属性
this.age = age //父的属性
this.fn = ()=>{ //父的方法
console.log('父函数');
}
}
say(){ //父的方法
console.log(this.name);
}
}
let f = new father('父','18') //父的实例化
class child extends father{ //子继承父
constructor(name,age){ //子的构造函数
super(name,age) //子继承父的属性
this.child = '子' //子自己的属性
}
cn(){
console.log(this); //子自己的方法
}
}
let child1 = new child(f.name,f.age) //子可以调用父的属性
console.log(child1);
child1.fn() //子可以调用父的方法
child1.say() //子可以调用父的方法
//class构造函数里的方法和外面的方法是一样的,只是写法不一样
本章介绍继承属于自己的一个理解,加深一下基本印象,如有错误,还请指出