You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript类私有成员#manufacturer声明及子类访问问题求助

问题分析与解决方案

核心问题原因

  1. 私有字段的访问限制:#manufacturer是父类vehicle的私有字段,根据JavaScript规则,私有字段只能在定义它的类内部直接访问,外部(包括子类实例)无法通过实例.字段名的方式直接访问。所以你执行console.log(d.manufacturer)时,相当于访问一个不存在的公共属性,结果自然是undefined。
  2. 子类重复定义私有字段的错误:如果在子类中定义#manufacturer,这会创建一个属于子类自己的私有字段,和父类的#manufacturer完全独立,而且子类仍然无权访问父类的私有字段,这样做不仅解决不了问题,还会导致逻辑混乱甚至报错。

修复后的代码

在父类中为#manufacturer添加getter方法,让外部可以合法访问该私有字段;同时修正父类中name getter的循环引用问题:

// task 1
class vehicle {
  #manufacturer;
  #name; // 改为私有字段避免getter循环引用

  constructor(manufacturer, name) {
    this.#manufacturer = manufacturer;
    this.#name = name;
  }

  // 为私有字段#manufacturer添加getter
  get manufacturer() {
    return this.#manufacturer;
  }

  get name() {
    return this.#name; // 返回私有字段,避免循环递归
  }
}

class car extends vehicle {
  #type;
  constructor(manufacturer, name, type) {
    super(manufacturer, name);
    this.#type = type;
  }

  get type() {
    return this.#type;
  }

  set type(value) {
    if (value.length > 3) this.#type = value;
  }
}

class motorcycle extends vehicle {
  #motortype; // 改为私有字段,保持封装性
  constructor(manufacturer, name, motortype) {
    super(manufacturer, name);
    this.#motortype = motortype;
  }

  get motortype() {
    return this.#motortype;
  }

  set motortype(value) {
    if (value.length > 3) {
      this.#motortype = value;
    }
  }
}

const e = new motorcycle('audi', 'a3', 'sport');
console.log(e.motortype);
e.motortype = 'supersport';
console.log(e.motortype);

const d = new car('bmw', 'm2', 'cool');
console.log(d.type);
d.type = 'lazy';
console.log(d.type);
console.log(e.name);
console.log(e.motortype);
console.log(d.manufacturer); // 现在可以正确获取到'bmw'

关键说明

  • 私有字段的封装性:私有字段的设计目的是隐藏内部实现,只暴露必要的访问接口(getter/setter),这是面向对象封装的核心原则。
  • 避免循环递归:原父类中get name() { return this.name; }会触发无限递归,因为访问this.name会再次调用getter,将name改为私有字段#name即可解决。
  • 子类的正确访问方式:子类不需要重新定义父类的私有字段,通过父类提供的getter方法就能合法访问父类的私有字段。

内容的提问来源于stack exchange,提问作者Davidino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 06:40:37