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

JS面向对象编程:跨文件调用类方法实现经理下属数组存储需求

需要调整的核心逻辑如下


1. 修正employee.js代码

移除不必要的manager依赖和全局实例,修正实例引用逻辑:

class Employee {
    constructor(name, title, salary, boss=null)
    {
        this.name = name;
        this.title = title;
        this.salary = salary;
        // 字段名对齐预期输出的manager
        this.manager = boss;
        // 存在上级时直接调用上级的addEmployee方法添加当前实例
        if (boss) {
            boss.addEmployee(this);
        }
    }
}

module.exports = Employee;

2. 修正manager.js代码

修正父类构造传参顺序,对齐数组字段命名,移除测试代码:

const Employee = require('./employee.js');

class Manager extends Employee {
    constructor(name, title, salary, boss=null) {
        // 按Employee的参数顺序传递给父类构造
        super(name, title, salary, boss);
        // 字段名对齐预期输出的employees
        this.employees = [];
    }

    addEmployee(employee) {
        this.employees.push(employee);
    }
}

module.exports = Manager;

3. 新增独立入口文件index.js存放测试逻辑

避免循环依赖导致的初始化异常,单独执行测试代码:

const Manager = require('./manager.js');
const Employee = require('./employee.js');

// 首字母大写完全匹配预期输出格式
let annie = new Manager('Annie', 'Director', 100000);
let alvy = new Employee('Alvy', 'Analyst', 75000, annie);

console.log(annie);

执行node index.js即可输出符合要求的结构,实例循环引用会被Node自动标记为[Circular *1]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:24:01