<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
//类的声明与实例化
function Animal1() {
this.name = name;
}
class Animal2 {
constructor() {
this.name = name;
}
}
console.log(new Animal1(), new Animal2());
//借助构造函数实现继承
function Parent1() {
this.name = 'parent1';
}
function Child1() {
Parent1.call(this); //将父级构造函数的this指向子构造函数实例上
this.type = 'child1';
}
console.log(new Child1());
//缺点:无法实现父类原型链上的属性和方法,只实现了部分继承
//借助原型链实现继承
function Parent2() {
this.name = 'parent2';
this.play = [1, 2, 3];
}
function Child2() {
this.type = 'child2';
}
Child2.prototype = new Parent2();
var s1 = new Child2();
var s2 = new Child2();
s1.play.push(4);
console.log(s1.play, s2.play);
// 缺点:一个子类的实例原型从父类构造函数中继承来的共有属性就会直接影响到其他子类
//组合方式
function Parent3() {
this.name = 'parent3';
this.play = [1, 2, 3];
}
function Child3() {
Parent3.call(this);
this.type = 'child3';
}
Child.prototype = new Parent();
var s3 = new Child3();
var s4 = new Child3();
s3.play.push(4);
console.log(s3.play, s4.play);
//缺点:父构造函数执行了两次(没必要)
//组合继承的优化一
function Parent4() {
this.name = 'parent4';
this.play = [1, 2, 3];
}
function Child4() {
Parent3.call(this);
this.type = 'child4';
}
Child.prototype = Parent.prototype;
var s5 = new Child4();
var s6 = new Child4();
s5.play.push(4);
console.log(s5.play, s6.play);
console.log(s5 instanceof Child4, s5 instanceof Parent4);
//缺点:无法区分一个实例是子构造器还是父构造器的实例
//组合继承的优化二
function Parent5() {
this.name = 'parent4';
this.play = [1, 2, 3];
}
function Child5() {
Parent3.call(this);
this.type = 'child4';
}
Child5.prototype = Object.create(Parent5.prototype);
Child5.prototype.constructor = Child5;
var s7 = new Child5();
console.log(s7 instanceof Child4, s7 instanceof Parent4);
console.log(s7.constructor);
</script>
</body>
</html>