2021-04-08 09:28:35
在直播App开发搭建的Web前端开发中,JavaScript的继承是实现代码复用和模块化的重要手段。以下是ES5和ES6中常见的继承方式及其详细说明:
ES5中的继承方式1. 构造函数继承(call/apply)通过call()或apply()方法改变this指向,实现属性继承。示例:
function Phone(color) { this.color = color; this.show = function() { console.log("颜色是:" + this.color); };}function Vivo(color) { Phone.call(this, color); // 继承Phone的属性}var vivo = new Vivo("黄色");vivo.show(); // 输出: "颜色是:黄色"特点:
通过将子类的原型指向父类实例,实现方法继承。示例:
function Person(name) { this.name = name; this.eat = function() { console.log(this.name + "在吃饭"); };}function Player() {}Player.prototype = new Person("张三"); // 继承Person的方法var player = new Player();player.eat(); // 输出: "张三在吃饭"滑历特点:
结合构造函数继承和原型链继承,弥补两者缺陷。示例:
function Car(color) { this.color = color;}function Passat(color, type) { Car.call(this, color); // 继承属性 this.type = type;}Passat.prototype = new Car(); // 继承方法Passat.prototype.run = function() { console.log(this.color + " " + this.type + "在行驶");};var passat = new Passat("黑色", "帕萨特");passat.run(); // 输出: "黑色 帕萨特在行驶"特点:
通过遍历父类属性并复制到子类,实现浅拷贝继承。示例:
function MingXing(name) { this.name = name; this.sing = function() { console.log(this.name + "在唱歌"); };}var obj = { extend: function(target) { for (var key in target) { this[key] = target[key]; } }};obj.extend(new MingXing("周杰伦"));obj.sing(); // 输出: "周杰伦在唱歌"特点:
ES6通过class和extends关键字简化继承,底层仍基于原型链。示例:
class Fu { constructor(x, y) { this.x = x; this.y = y; } show() { console.log(`x=${this.x}, y=${this.y}`); }}class Zi extends Fu { constructor(x, y) { super(x, y); // 必须调用super() }}const zi = new Zi(1, 2);zi.show(); // 输出: "x=1, y=2"特点:
ES5继承:
简单场景用构造函数继承或原型链继承。
推荐组合继承平衡属性与方法继承。
拷贝继承适合轻量级混入需求。
ES6继承:
优先使用class和extends,代码更易维护。
需注意super()必须在子类constructor中优先调用。
在直播App开发中,若需兼容旧浏览器(如IE11),仍需使用ES5方案;现代项目建议直接采用ES6语法,结合Babel转译保障兼容性。