JS继承
类:封装,继承,多态
- 封装:类也是个函数,把实现一个功能代码进行封装,以此实现低耦合高内聚
- 多态:重载,重写
- 重写:子类重写父类上的方法(伴随着继承运行)
- 重载:相同的方法,由于参数或者返回值不同,具备了不同的功能(js中不具备严格意义上的重载,js的重载:同一个方法,根据传参不同实现不同的功能)
- 继承:子类继承父类中的方法
function fn(x,y){
if(y===undefined){
....
} else {
...
}
}
js中的继承和其他语言继承不同
继承的目的:让子类的实例同事也具备父类中私有的属性和公共的方法
- 原型继承(子类的原型等于父类的实例)
- Child.prototype = new Parent;子类的原型指向父类的实例
- 父类中私有的和公有的属性方法,最终都变为子类实例公有的
- 和其他语言不同,原型继承并不会把父类的属性方法拷贝给子类,而是让子类实例基于__proto__原型链找到自己定义的属性和方法:‘指向、查找’方式
- c1.proto.xxx=xxx 修改子类原型(原有父类中的一个实例)中的内容,内容被修改后,对子类的其他实例有影响,但是对父类的实例不会有影响
- c1.proto.proto.xxx=xxx 直接修改的是父类原型,这样不仅会影响其他弗雷德实例,也影响其他子类的实例
function Parent(){
this.x =100;
}
Parent.prototype.getX = function getX(){
return this.x;
}
function Child(){
this.y = 200;
}
Child.prototype = new Parent;
Child.prototype.getY = function getY(){
return this.y;
}
let c1 = new Child;
console.log(c1);
- call继承
- 只能继承父类中私有的,不能继承父类中公有的
- 把父类私有的变为子类私有的
- 寄生组合式继承(call继承+另类原型继承)
function Parent(){
this.x =100;
}
Parent.prototype.getX = function getX(){
return this.x;
}
function Child(){
Parent.call(this);
this.y = 200;
};
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.getY = function getY(){
return this.y;
}
let c1 = new Child;
console.log(c1);
ES6中创建类和继承
class Parent{
constructor(){
this.x=100;
}
getX(){
return this.x
}
}
class Child extends Parent{
constructor(){
super();
this.y=200;
}
getY(){
return this.y;
}
}
Child();
let c1= new Child;
console.log(c1);