混合继承
function Parent (value) {
this.value=value
};
Parent.prototype.getValue = function () {
console.log(this.value);
}
function Child (value) {
//通过call,使得子继承父的属性
//以下函数为子类的构造函数
Parent.call(this,value);
}
// 通过protoType,继承父亲的方法
Child.prototype = new Parent();
let li = new Child ('li');
li.getValue();
这个的好处是:
1. 构造函数可以传参数
2. 不会和父类引用属性共享
坏处:
继承父类函数的时候调用了父类构造函数,导致子类的原型上多了不需要的父类属性,存在内存上的浪费
寄生组合继承
function Parent(value) {
this.value = value;
}
Parent.prototype.getValue = function () {
console.log(this.value);
};
function Child(value) {
Parent.call(this, value);
}
Child.prototype = Object.create(Parent.prototype, {
constructor: {
value: Child,
enumerable: false,
writable: true,
configurable: true,
},
});
let li = new child('li');
li.getValue();
//将父类原型赋值给子类,并且将构造函数赋值给子类
calss继承
class Parent {
constructor(value){
this.value=value;
}
getValue(){
console.log(this.value);
}
}
class Child extends Parent {
constructor (value){
super(value);
}
}
let li = new child ('li');
console.log(li.value);
li.getValue();
- calss比函数多了一条原型链
本来,Child.prototype._proto_=Parent.prototype; 现在多出来一条,Child._proto_=Parent
- super()负责初始化this,相当于ES5中的call和apply方法
- 在普通方法中指向父类的原型对象,在静态方法中指向父类