一、继承
1、类级别的继承
- 前端没有太强的类的概念 因为前端对表抽象的程度不高
2、构造函数继承
在子类中显示的call调用父类
3、原型链继承
- 隐式原型链
缺点:属性不够动态
4、组合继承
- 属性通过构造函数继承
- 方法通过原型链继承
5、对象级别的继承
二、代码示例:
1、01_构造函数继承.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>02_借用构造函数继承</title>
</head>
<body>
<!--
构造函数继承
在子类中显示的call调用父类
方式2: 借用构造函数继承(假的)
1. 套路:
1. 定义父类型构造函数
2. 定义子类型构造函数
3. 在子类型构造函数中调用父类型构造
2. 关键:
1. 在子类型构造函数中通用super()调用父类型构造函数
-->
<script type="text/javascript">
function Person(name, age) {
this.name = name
this.age = age
}
function Student(name, age, price) {
Person.call(this, name, age) // this.Person(name, age)
this.price = price
}
var s = new Student('Tom', 20, 12000)
console.log(s.name, s.age, s.price)
</script>
</body>
</html>
2、02_原型链继承.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>01_原型链继承</title>
</head>
<body>
<!--
方式1: 原型链继承
1. 套路
1. 定义父类型构造函数
2. 给父类型的原型添加方法
3. 定义子类型的构造函数
4. 创建父类型的对象赋值给子类型的原型
5. 将子类型原型的构造属性设置为子类型
6. 给子类型原型添加方法
7. 创建子类型的对象: 可以调用父类型的方法
2. 关键
1. 子类型的原型为父类型的一个实例对象
隐式原型链
缺点:属性不够动态
-->
<script type="text/javascript">
function Supper() { //父类型
this.superProp = 'The super prop'
}
Supper.prototype.showSupperProp = function () {
console.log(this.superProp)
}
function Sub() { //子类型
this.subProp = 'The sub prop'
}
Sub.prototype = new Supper()
Sub.prototype.constructor = Sub
Sub.prototype.showSubProp = function () {
console.log(this.subProp)
}
// 创建子类型的实例
var sub = new Sub()
// 调用父类型的方法
sub.showSubProp()
// 调用子类型的方法
sub.showSupperProp()
</script>
</body>
</html>
3、03_组合继承.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>03_组合继承</title>
</head>
<body>
<!--
组合继承
属性通过构造函数继承
方法通过原型链继承
方式3: 原型链+借用构造函数的组合继承
1. 利用原型链实现对父类型对象的方法继承
2. 利用super()借用父类型构建函数初始化相同属性
-->
<script type="text/javascript">
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.setName = function (name) {
this.name = name
}
function Student(name, age, price) {
Person.call(this, name, age) //得到父类型的属性
this.price = price
}
Student.prototype = new Person() //得到父类型的方法
Student.prototype.constructor = Student
Student.prototype.setPrice = function (price) {
this.price = price
}
var s = new Student('Tom', 12, 10000)
s.setPrice(11000)
s.setName('Bob')
console.log(s)
console.log(s.constructor)
</script>
</body>
</html>
4、04_对象级别的继承.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
<!--
object.create (对象级别的继承)
object.create(null):创建一个干净的对象(无原型链)
-->
<script type="text/javascript">
var father={name:"马云"};
var son = Object.create(father)
debugger
</script>
</html>