JS使用extends实现类继承时如何让子类通过构造传参继承父类属性值
解决方案:JavaScript extends继承父类构造传参的正确实现
核心错误原因
- 子类构造调用
super()时未传入父类构造要求的4个入参,导致父类初始化的x/y/w/h均为undefined,后续数值运算返回NaN - 单独创建的
parent实例与child实例为完全独立的对象,类继承是原型层面的逻辑,不会自动同步两个独立实例的属性
正确实现方案
方案1:子类构造透传参数给父类
适合直接创建子类实例的场景,不需要额外生成父类实例:
class Parent { constructor(x, y, w, h) { this.x = x; this.y = y; this.w = w; this.h = h; } } class Child extends Parent { // 子类构造接收和父类一致的入参 constructor(x, y, w, h) { // 将入参透传给父类构造完成属性初始化 super(x, y, w, h); this.pt1 = {x: this.x, y: this.y}; this.pt2 = {x: this.x + this.w, y: this.y}; this.pt3 = {x: this.x + this.w, y: this.y + this.h}; this.pt4 = {x: this.x, y: this.y + this.h}; } } // 直接给子类构造传入参数即可 let child = new Child(300, 50, 50, 200); console.log(child.pt1) // 输出 {x: 300, y: 50} console.log(child.pt3) // 输出 {x: 350, y: 250}
方案2:基于已有的父类实例创建子类实例
适合已经生成了父类实例,需要基于该实例的属性生成子类实例的场景:
class Parent { constructor(x, y, w, h) { this.x = x; this.y = y; this.w = w; this.h = h; } } class Child extends Parent { // 构造函数接收父类实例作为入参 constructor(parentInstance) { // 从父类实例提取属性传给父类构造 super(parentInstance.x, parentInstance.y, parentInstance.w, parentInstance.h); this.pt1 = {x: this.x, y: this.y}; this.pt2 = {x: this.x + this.w, y: this.y}; this.pt3 = {x: this.x + this.w, y: this.y + this.h}; this.pt4 = {x: this.x, y: this.y + this.h}; } } // 先创建父类实例,再传入子类构造 let parent = new Parent(300, 50, 50, 200); let child = new Child(parent); console.log(child.pt1) // 输出 {x: 300, y: 50} console.log(child.pt3) // 输出 {x: 350, y: 250}
内容的提问来源于stack exchange,提问作者Justin
相关产品推荐
相关产品推荐

