前言
继承是面向对象中最重要的概念
js的继承分为:
- 原型链继承
- 构造继承
- 组合式继承
- 原型式继承
- 寄生式继承
- 寄生组合式继承
- class类继承(ES6新语法、语法糖)
原型链继承
原型中的引用对象会被所有实例对象共享,并且创建出来的子类型不能向父类型传参
function Person1() {
this.name = '人'
this.age = '22'
this.color = ['red']
}
function Student1() {
this.type = '学生'
}
Student1.prototype = new Person1()
构造函数继承
虽然解决了原型链继承不能向父类型传参和引用类型公用的问题,但是父类型原型定义的方法没法被访问
//构造式继承
function Person2() {
this.name = '人'
this.age = '22'
this.color = ['red']
this.getColor = function() {
console.log(`我是${this.color}`)
}
}
Person2.prototype.getName = function() {
console.log(`我是${this.name}`)
}
function Student2() {
Person2.call(this)
this.type = '学生'
}
let s2 = new Student2()
s2.name = '哈哈'
组合继承
补齐了原型链继承和构造函数继承的缺点,但是会调用两次父类构造函数
function Person3() {
this.name = '人'
this.age = '22'
this.color = ['red']
this.getColor = function() {
console.log(`我是${this.color}`)
}
}
Person3.prototype.getName = function() {
console.log(`我是${this.name}`)
}
function Student3() {
Person3.call(this)
this.type = '学生'
}
Student3.prototype = new Person3()
Student3.prototype.constructor = Student3
原型式继承
Object.create 浅拷贝,引发了引用类型共用问题
let person4 = {
name:'人',
color: ['red'],
getName: function() {
return `我是${this.name}`
}
}
let p4 = Object.create(person4)
寄生式继承
在原型式继承上,新添加一些方法
let person5 = {
name:'人',
color: ['red'],
getName: function() {
return `我是${this.name}`
}
}
function clone(proto) {
let s5 = Object.create(proto)
s5.getColor = function() {
return this.color
}
return s5
}
let p5 = clone(person5)
寄生组合式继承
解决了组合继承调用两次父类构造函数的问题
//寄生式组合
function Person6() {
this.name = '人'
this.age = '22'
this.color = ['red']
this.getColor = function() {
console.log(`我是${this.color}`)
}
}
Person6.prototype.getName = function() {
console.log(`我是${this.name}`)
}
function Student6() {
Person2.call(this)
this.type = '学生'
}
function clone1(Parent, Student) {
Student.prototype = Object.create(Parent.prototype)
Student.prototype.constructor = Student
}
Student6.prototype.getType = function() {
console.log(`我是${this.type}`)
}
clone(Person6, Student6)
class类继承
寄生组合式继承的语法糖
class Person7 {
constructor(name) {
this.name = name
}
getName = function() {
return this.name
}
}
class Student7 extends Person7 {
constructor(name, type) {
super(name)
this.type = type
}
getType = function() {
return this.name + this.type
}
}
调试地址
HTML-CSS-JS- IDE Pro -InsCode (csdn.net)
参考链接
大厂高频面试题:JavaScript继承 (baidu.com)
面试官: JavaScript如何实现继承?_js面试继承-CSDN博客