为什么JS子类继承了父类super()未指定的属性?
问题原因及解决办法
问题根源
你遇到的问题核心是子类调用父类构造函数时参数顺序不匹配:
- 父类
Product的构造函数参数顺序为(name, categorie, htPrice) - 子类
Laptop中调用super(name, htPrice)时,只传了两个参数,这会导致:- 第一个参数
name对应父类的name属性,赋值正确 - 第二个参数
htPrice被错误地传给了父类的第二个参数categorie,所以categorie被赋值为700 - 父类的第三个参数
htPrice没有收到任何值,因此被设为undefined
- 第一个参数
结合你的实例化代码:
let item1 = new Laptop('Dell', 'E-bay', 'dell-Latitue', 700)
子类构造函数的参数顺序是(company, store, name, htPrice),super(name, htPrice)实际传递的是'dell-Latitue'和700,完全对应上面的错误逻辑,最终出现属性值混乱的结果。
解决方法
方法1:修正super的参数顺序
如果需要保留父类的参数结构,调用super时严格按照父类的参数顺序传递,不需要的categorie可以传undefined:
class Laptop extends Product { constructor(company, store, name, htPrice) { // 按父类顺序传参,categorie传入undefined super(name, undefined, htPrice) this.company = company this.store = store } }
实例化后输出会变为:
Laptop {name: 'dell-Latitue', categorie: undefined, htPrice: 700, company: 'Dell', store: 'E-bay'}
方法2:给父类参数设置默认值(推荐)
如果父类的categorie不是所有子类都需要,给父类构造函数的categorie设置默认值,这样子类调用super时可以灵活省略该参数:
// 修改父类构造函数,给categorie添加默认值 class Product { constructor(name, categorie = undefined, htPrice) { this.name = name this.categorie = categorie this.htPrice = htPrice } } // 子类调用super时只需传递必要参数 class Laptop extends Product { constructor(company, store, name, htPrice) { super(name, undefined, htPrice) this.company = company this.store = store } }
额外说明
JavaScript中,子类调用super()会完整执行父类的构造函数逻辑,父类中定义的所有属性都会被添加到子类实例上——不存在“仅指定继承部分属性”的说法,除非你在子类构造函数中手动删除不需要的属性(比如delete this.categorie),但这种做法不推荐,会破坏类的继承结构。
内容的提问来源于stack exchange,提问作者Youssef
相关产品推荐
相关产品推荐

