考察方式:
类的声明:
- 通过构造函数声明
- ES6 class关键字声明
//构造函数声明-thisfunction Animal(){this.name='name'}//class关键字声明class Animal2{constructor(){this.name="name1"}}
类的实例化:
- 用new关键字实例化
new 类名(参数)
类的继承:
避免直接操作proto
- 借助构造函数实现继承:子类不能继承父类的原型对象上的方法
- 借助原型链实现继承:因为引用了同一个对象,导致继承自同一父类的两个子类之间 不能相互隔离
- 组合方式实现继承:父类的构造函数会执行两遍
- 组合方式优化1:不能判断是由子类实例化还是父类实例化
- 组合方式优化2:
- es6关键字实现继承:
// 借助构造函数实现继承function Parent1(){this.name="parent"}Parent1.prototype.say=function(){console.log(hello)}function Child1(){//apply也可以,改变函数运行上下文Parent1.call(this)this.type="child1"}console.log(new Child1().say())//报错//借助原型链实现继承function Parent2(){this.name="andy"}function Child2() {this.type="整数"}Child2.prototype=new Parent1()//组合方式实现继承function Parent3() {this.name="bob"this.play=[1,2,3]}function Child3() {Parent3.call(this)this.type="浮点数"}Child3.prototype=new Parent3()var s1=new Child3()var s2=new Child3()//组合继承的优化1function Parent4() {this.name="bob"this.play=[1,2,3]}function Child4() {Parent3.call(this)this.type="浮点数"}Child4.prototype=Parent4.prototype//组合继承的优化function Parent5() {this.name="bob"this.play=[1,2,3]}function Child5() {Parent5.call(this)this.type="浮点数"}Child5.prototype=Object.create(Parent5.prototype)Child5.prototype.constructor=Child5
//ES6实现class ColorPoint extends Point {constructor(x, y, color) {super(x, y); // 调用父类的constructor(x, y)this.color = color;}toString() {return this.color + ' ' + super.toString(); // 调用父类的toString()}}
