组合式继承
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 组合式继承
// 原型链继承不能继承属性,构造函数不能够继承方法,把两个结合
function Animal(name, age) {
this.name = name
this.age = age
this.hobby = []
}
Animal.prototype.say = function () {
console.log('说话')
}
Cat.prototype = new Animal()
function Cat(name, age) {
Animal.call(this, name, age)
}
const cat1 = new Cat('11', 2)
const cat2 = new Cat('22', 3)
cat1.hobby.push('吃')
cat2.hobby.push('喝')
console.log(cat1)
console.log(cat2)
cat1.say()
</script>
</body>
</html>
寄生式继承
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 组合式继承
// 原型链继承不能继承属性,构造函数不能够继承方法,把两个结合
function Animal(name, age) {
this.name = name
this.age = age
this.hobby = []
}
Animal.prototype.say = function () {
console.log('说话')
}
Cat.prototype = Object.create(Animal.prototype)//{__proto__:Animal.protptype}
function Cat(name, age) {
Animal.call(this, name, age)
}
const cat1 = new Cat('11', 2)
const cat2 = new Cat('22', 3)
cat1.hobby.push('吃')
cat2.hobby.push('喝')
console.log(cat1)
console.log(cat2)
cat1.say()
</script>
</body>
</html>