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

Node.js中类实例导出后,多文件导入是否为同一实例?

Will importing this exported class instance create a new instance each time?

Great question! Let me break this down clearly for you:

Straight Answer

No, you won't get a new instance every time you import the file. The http in both view/splash.js and view/groups.js will be the exact same instance. This is exactly how module systems (both CommonJS with require and ES Modules with import) work in JavaScript environments like Node.js or bundlers such as Webpack/Vite.

Why This Happens

JavaScript modules are inherently singleton-like. Here's the step-by-step breakdown of what happens:

  1. When the first file (say splash.js) imports ../../utils/http, the module's code runs in full:
    • The _Http class is defined
    • A single instance of _Http is created and assigned to Http
    • That instance is exported as the default value
  2. The runtime caches this exported instance. Any subsequent imports (like in groups.js) skip re-running the module code entirely—they just pull the already cached instance directly.

How to Verify It Yourself

If you want to confirm this is true, you can add a unique identifier to your _Http class and log it in both files:

// utils/http.js
class _Http {
  constructor() {
    // Generate a random unique ID when the instance is created
    this.instanceId = Math.random();
  }
}
let Http = new _Http();
export default Http;

Then in your two view files:

// view/splash.js
import http from '../../utils/http';
console.log('Splash instance ID:', http.instanceId); // Logs a specific random number
// view/groups.js
import http from '../../utils/http';
console.log('Groups instance ID:', http.instanceId); // Logs the EXACT same number as above

The matching IDs prove you're working with the same instance across both imports.

Note on Singleton Pattern

You're right to recognize this as a form of the singleton pattern. Using module-level exports to create a single instance is actually one of the most straightforward and reliable ways to implement singletons in JavaScript, since it leverages the module system's built-in caching instead of relying on manual singleton logic (like checking if an instance already exists in the constructor).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:25:26