圣杯模式
function inherit(son, father) {
function T () {};
son.prototype = new T();
T.prototype = father.prototype;
son.prototype.constructor = son;
son.prototype.uber = father.prototype;
}
原型上的constructor默认指向他的构造函数,son的constructor应该指向son
我们希望构造出来的对象能够找到自己的超类——超级父类(究竟继承自谁)应该使用super,但super是保留字,所以使用uber
雅虎程序员写的圣杯模式继承,利用了立即执行函数,相对来说更高级
inherit = (function () {
var T = function () {};
return function (son, father) {
T.prototype = father.prototype;
son.prototype = new T();
son.prototype.constructor = son;
son.prototype.uber = father.prototype;
}
}());
构造函数继承
类的继承
- extends 继承,用于类的定义
- super
- 当做函数调用,表示父类构造函数
- 当做对象使用,表示父类的原型
class Father {
constructor (type, name, age, sex) {}
methods() {}
}
class Son extends Father{
constructor (name, age, sex) {
super(type, name, age, sex)
}
}
注意:ES6要求,如果定义了constructor,并且该类是子类,则必须在constructor的第一行手动调用父类的构造函数,如果子类不写constructor,则会自动调用父类构造器,该构造器需要的参数和父类一致
小知识:JS实现抽象类
抽象类:一般是父类,不能通过该类创建对象
class Father {
constructor (type, name, age, sex) {
if (new target === Feater) {
throw new TypeError("不能直接创建Father的对象,应该通过子类创建")
}
}
methods() {}
}