原型继承
通过prototype把子类的原型绑到父类的实例上,子类就可以调用父类的公有属性和方法、私有的属性和方法。但是这种方式实现继承,无论父类中公有的属性和方法还是私有的属性和方法,都会变成子类公有的属性和方法,这样子类就可以重写父类的属性和方法,也有影响父类的其他实例。
function Parent(x){
this.x = x;
};
Parent.prototype.getX=function(){
console.log(x)
};
function Child(y){
this.y = y;
};
Child.prototype = new Parent(100);
Child.prototype.constructor = Child;
Child.prototype.getY=function(){
console.log(y)
};
let child = new Child(200);
child.getX();
child.getY();
call继承
通过call改变this指向问题,把父类公有的属性和方法当作函数来执行,但是不可以使用父类的私有属性和方法。
function parent(x) {
this.x = x;
}
parent.prototype.getX = function () {
console.log(this.x);
}
function children(y) {
parent.call(this, 200);
this.y = y
}
children.prototype.getY = function () {
console.log(this.y);
console.log(this.x)
}
let child = new children(100);
child.getY();
寄生组合继承
这个就好多了,其实就是call+类似原型继承,父类公有的属性和方法也会成为子类公有的属性和方法,父类私有的属性和方法也会成为子类私有的属性和方法。very good!
function parent(x) {
this.x = x;
}
parent.prototype.getX = function () {
console.log(this.x);
}
child.prototype = Object.create(parent.prototype);
child.prototype.constructor = child;
function child(y) {
parent.call(this, 100);
this.y = y;
}
child.prototype.getY = function () {
console.log(this.y);
}
let kid = new child(200);
kid.getX();
kid.getY();
es6中class
非常如此之方便的class来了,也是父类的公有和私有对应是子类的公有和私有的属性和方法
class parent {
constructor(x) {
this.x = x;
}
getX = function () {
console.log(this.x);
}
}
class child extends parent {
constructor(y) {
super(100);
this.y = y;
}
getY = function () {
console.log(this.y);
}
}
let ch = new child(200)
ch.getX()
ch.getY()