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

Node.js问题:调用runner.one为何runner.two也执行?如何仅执行前者?

问题原因

你在配置模块里直接执行了new one()和new two(),当你import runner from "./"的时候,整个模块的顶层代码都会被执行——不管你后续是否访问runner.two,two的构造函数都会在模块加载阶段就自动运行了。

解决方案

以下几种方式可以实现「仅在访问对应属性时才实例化类」的需求:

方案1:直接导出类,按需手动实例化

修改配置代码:

import { one, two } from './your-class-file'; // 替换为类定义文件的路径

export default {
  one,
  two
}

调用代码:

import runner from "./";
const instanceOne = new runner.one(); // 此时才会执行one的构造函数
// 不手动new runner.two的话,two的构造函数不会执行

方案2:导出实例化函数,调用时才触发

修改配置代码:

import { one, two } from './your-class-file';

export default {
  getOne: () => new one(),
  getTwo: () => new two()
}

调用代码:

import runner from "./";
runner.getOne(); // 仅执行one的构造函数
// 不调用runner.getTwo()的话,two不会执行

方案3:用ES6 getter属性,访问时自动懒实例化

修改配置代码:

import { one, two } from './your-class-file';

let instanceOne = null;
let instanceTwo = null;

export default {
  get one() {
    if (!instanceOne) {
      instanceOne = new one();
    }
    return instanceOne;
  },
  get two() {
    if (!instanceTwo) {
      instanceTwo = new two();
    }
    return instanceTwo;
  }
}

调用代码:

import runner from "./";
runner.one; // 此时才执行one的构造函数
// 不访问runner.two的话,two不会执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 03:01:00