/**
* JavaScript继承的几种方式
* 整理者:Bannings
*/
/**
* @description 父类Plane,抽象飞机
* @constructor
* @param {string} color 表示飞机的颜色
* @param {number} speed 表示飞行速度
*/
function Plane(color,speed){
this.color = color;
this.speed = speed;
}
Plane.prototype.fly = function(){
console.log("flying");
}
/**
* 原型链继承
* 缺点:
* 1、共享引用类型数据会产生数据污染
* 2、不能传参
* 3、需要手动修复构造函数
*/
function Airliner(){};
airliner.prototype = new Plane("white",280);
airliner.prototype.constructor = Airliner;//修复构造函数
/**
* 构造继承
* 优点:
* 1、独享属性,不会产生数据污染
* 2、可以传参
* 缺点:
* 1、无法继承到父类原型上的方法(致命缺点)
*/
function Airliner(color,speed){
Plane.call(this,color,speed);
this.passenger = [];
};
/**
* 组合继承
* 优点:
* 1、属性和方法都是从父类继承的(代码复用)
* 2、继承的属性是私有的(互不影响)
* 3、继承的方法都在原型里(函数复用)
* 缺点:
* 1、调用了两次父类的构造函数(影响性能)
* 2、子类和父类属性重复(代码冗余)
*/
function Airliner(color,speed){
Plane.call(this,color,speed);
this.passenger = [];
}
Airliner.prototype = new Plane();//继承原型上的属性和方法
Airliner.prototype.constructor = Airliner;//修复构造函数
Airliner.prototype.watchTv = function(){//添加自定义方法
console.log("watching TV");
}
/**
* 寄生组合继承
* 优点:
* 1、解决了组合继承存在的问题
*/
function Airliner(color,speed){
Plane.call(this,color,speed);
this.passenger = [];
}
inheritPrototype(Airliner,Plane);
function inheritPrototype(child,parent){
var Super = function(){};
Super.prototype = parent.prototype;
child.prototype = new Super();
child.prototype.constructor = child;
}
【JavaScript】继承的几种方式
最新推荐文章于 2022-04-29 17:06:16 发布