1.继承实例属性
Super为父类,Sub继承父类。
function Super(prop1, prop2) {
this.prop1 = prop1;
this.prop2 = prop2;
}
function Sub(prop1, prop2, prop3, prop4) {
//this指向Sub,把它传入Super中,不用new出一个Super实例,把Super当作函数,用以设置Sub的prop1,prop2的属性。
Super.call(this, prop1, prop2);
this.prop3 = prop3;
this.prop4 = prop4;
}
2.继承原型属性
有的方法存放在实例的原型Super.prototype中,需要指定Sun.prototype的原型为Super.prototype。
//建立原型关系
Sub.prototype = Object.create(Super.prototype);
//指向回Sub
Sub.prototype.constructor = Sub;
//设置子类的原型实例上的方法
Sub.prototype.methodB = function() {};
3.确保instanceof正常工作
subInstance instanceof Super
Super.prototype.isPrototypeOf(sunInstance)
4.覆写
可以直接添加Sub.prototype的同名方法,完成覆写。调用时是子类实例方法优先。
5.反模式
在ES5和Object.create()之前,常用的解决方案是通过调用父构造函数来创建子构造函数:
Sun.prototype = new Super();
不推荐!!