本文共 1589 字,大约阅读时间需要 5 分钟。
在 JavaScript 中,最基础的继承方式是通过原型链实现的子类继承父类。在以下代码中,Son
类通过将其原型链指向 Father
实例的原型链,从而继承了 Father
的属性和方法。
function Father() { this.height = "180cm";}function Son() {}var father = new Father();var son = new Son();Son.prototype = father; // 使 son 的原型链指向 father 的原型
这样,son
实例的原型链会逐步归属于 father
实例以及 Father
构造函数。具体原型链结构如下:
son.__proto__ → son.prototype = Father.prototype → father.__proto__ → Father.prototype
优点:简单好理解
缺点:继承了父亲所有的属性缺点:无法仅继承特定的属性或方法这种继承方式的特点是多个子类可以互相继承。例如,Brother1
和 Brother2
mutually 可以继承对方的属性和方法。
function Brother1() { this.name = name; this.age = age;}function Brother2() {}var brother1 = new Brother1();var brother2 = new Brother2();Brother1.prototype = Brother2.prototype;
这样,Brother1
和 Brother2
的原型链都会指向 Brother2.prototype
。
优点:相互继承
缺点:修改任何一个子类的原型会影响另一个子类缺点:不支持单独继承特定属性或方法这种方式通过 Function.call
将子类的 this
指向父类实例,从而继承父类的属性和方法。这种方式通常在特定场景下使用,以避免使用原型链,直接继承父类属性。
function Father(name, age, sex) { this.name = name; this.age = age; this.sex = sex;}function Son(name, age, sex) { Father.call(Son, name, age, sex);}
优点:不用设计原型链结构
缺点:需要强制继承父类的所有属性和方法缺点:不支持添加额外属性或方法圣杯模式通过引入一个中间类(Templator)来实现特定于子类的继承方式。这种方式可以在继承父类属性的同时,避免来自其他子类的干扰。
function Father() {}function Son() {}function Temp() {}// 创建中间商实例var temp = new Temp();// Son inherit from Temp,并记录构造函数Son.prototype = temp;Son.prototype.constructor = Son;// 添加原型链指向FatherSon.prototype.uber = Father.prototype;var son = new Son();// son 的原型链结构:Son.prototype → temp → Father.prototype
优点:仅继承特定的父类属性和方法
缺点:引入了中间商类缺点:需要手动绑定构造函数通过以上多种继承方式,可以根据具体需求选择最合适的方案。你认为哪种方式最适合你的项目?
转载地址:http://xtrhz.baihongyu.com/