【JavaScript】继承的几种方式

/**
 * 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值