01.原型链继承
方式一: 原型链继承
1.套路
1.定义父类型构造函数
2.给父类型的原型添加方法
3.定义子类型构造函数
4.创建父类型的对象赋值给子类型的原型
5.将子类型的构造属性设置为子类型
6.给子类型原型添加方法
7.创建子类型的对象,可以调用父类型的方法
2.关键
1.子类型的原型为父类型的一个实际对象
实现代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>原型链继承</title>
</head>
<body>
<script>
//父类型
function Supper() {
this.supProp = 'Supper property'
}
Supper.prototype.showSupperProp = function () {
console.log(this.supProp)
}
//子类型
function Sub() {
this.subProp = 'Sub property'
}
//子类型的原型为父类型的一个实例对象
Sub.prototype = new Supper()
//让子类型的原型的constructor指向子类型(构造函数)
Sub.prototype.constructor = Sub
Sub.prototype.showSubProp = function () {
console.log(this.subProp)
}
var sub = new Sub()
sub.showSupperProp() //能执行说明有继承
sub.toString() //能够访问,查找顺序:Sub--->Sub.prototype(Object实例)--->Object原型对象 //toString() 是 Object原型对象 上的方法
//如果不加Sub.prototype.constructor = Sub
console.log(sub.constructor)//会指向Supper(错误) //constructor是原型对象上的属性,而现在的原型对象是new Supper()的实例,去读constructor读的是Supper
console.log(sub) //(图解)看constructor在哪里,Sub--->Supper--->Object
</script>
</body>
</html>
02.借用构造函数继承
方式2: 借用构造函数继承(假的)
1.套路:
1.定义父类型构造函数
2.定义子类型构造函数
3.在子类型构造函数中调用父类型构造
2.关键
1.在子类型构造函数中调用call()调用父类型构造函数
实现代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>借用构造函数继承(假的)</title>
</head>
<body>
<script>
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.name = name
// this.age = age
this.price = price
}
var s = new Student('Tom', 12, 120000)
console.log(s.name, s.age, s.price)
</script>
</body>
</html>
03.组合继承
实现代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>组合继承</title>
</head>
<body>
<script>
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 //修正constructor属性
Student.prototype.setPrice = function(price) {
this.price = price
}
var s1 = new Student('kate', 26, 12000)
s1.setName('yue')
s1.setPrice(16000)
console.log(s1.name, s1.age, s1.price)
</script>
</body>
</html>