Node.js中类实例导出后,多文件导入是否为同一实例?
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:
- When the first file (say
splash.js) imports../../utils/http, the module's code runs in full:- The
_Httpclass is defined - A single instance of
_Httpis created and assigned toHttp - That instance is exported as the default value
- The
- 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

