1.call()
能够传参构造函数,不能获取parent原型上的属性和方法
function Children(a, b){
Parent.call(this, a, b);
}
Parent.prototype.c = 'c';
Parent.prototype.getC = function(){};
let children = new Children(a, b);
children.a // a
children.b // b
children.c // undefined
children.getC // 报错 not a Function
2.prototype
能够获取parent原型上的属性和方法,不能传参构造父类的属性值
function Children(c){
this.c = c;
}
Parent.prototype.c = 'c';
Parent.prototype.getC = function(){};
let children = new Children(c);
children.a // a 不能传值构造
children.b // b 不能传值构造
children.c // c
children.getC // function
3.call() + prototype
能构造父类属性,也能拿到原型上的值,但是会构建2次实例,冗余
function Children(a, b, c){
Parent.call(this, a, b); // 实例了一次
this.c = c;
}
Parent.prototype.c = 'c';
Parent.prototype.getC = function(){};
Children.prototype = new Parent(); // 实例了一次
let children = new Children(c);
children.a // a
children.b // b
children.c // c
children.getC // function
4.拓展实例
能构造父类属性,也能拿到原型上的值,相当于是拓展了个Parent函数
function Children(a, b, c){
let obj = new Parent(a, b);
obj.c = c;
return obj;
}
Parent.prototype.d = 'd';
Parent.prototype.getD = function(){};
let children = new Children(a, b, c);
children.a // a
children.b // b
children.c // c
children.d // d
children.getD // function
5.ES6 class extends
class继承是把父类的this实例出来然后子类继承父类的this,如果没调用super(),则子类没有this
class Children{
constructor(a, b, c){
super(a, b); // super后才会有this
this.c = c;
}
}
let children = new Children(a, b, c);
children.a // a
children.b // b
children.c // c