一、类与实例
1、类的声明
function Animal(name){
this.name = name
}
class Animal1{
constructor(name){
this.name = name
}
}
2、类的实例化
new Animal('dog')
new Animal1('cat')
二、类与继承
1、继承方式
- 借助构造函数实现继承
function Parent1(){
this.name = 'parent'
}
function Child(){
Parent1.call(this)
this.type = 'child'
}
//子类不能继承父类原型对象上的方法
2、借助原型链实现继承
function Parent2(){
this.name = 'parent'
}
function Child2(){
this.type = 'Child2'
}
Child2.prototype = new Parent2()
//实例对象对原型属性的修改,实例之间的相互影响的
3、构造函数、原型组合方式
function Parent3() {
this.name = 'parent'
this.play = [1,2,3]
}
function Child3() {
Parent3.call(this);
this.type = 'child3';
}
Child3.prototype = new Parent3()
//结合了构造函数继承和原型继承的优点,同时避免了它们的缺点。
//但是这里的父级构造函数Parent3执行了两次,无法区分它是哪个构造函数直接实例化得来的
4、组合继承的优化
function Parent4() {
this.name = 'parent'
this.play = [1,2,3]
}
function Child4() {
Parent4.call(this);
this.type = 'child4';
}
Child4.prototype = Parent4.prototype;
//这时父类构造函数Parent4只执行了一次
//但是无法区分实例是父类构造函数实例化的还是子类实例化的
5、组合继承优化二(这是最完美的写法)
function Parent5() {
this.name = 'parent'
this.play = [1,2,3]
}
function Child5() {
Parent5.call(this);
this.type = 'child5';
}
Child5.prototype = Object.create(Parent5.prototype)
Child5.prototype.constructor = Child5
//做到了子类对象和父类对象的隔离