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

JavaScript内存泄漏疑问:实例化类X是否会引发内存泄漏?

Will instantiating this class cause a memory leak?

First, let's look at your code for reference:

class X { 
  constructor (socketObject, callback) { 
    this.socketObject = socketObject; 
    callback(null, socketObject); 
  } 
}
const socketObject = {hello:'world'};
new X (socketObject, function (err, res) { if(!err) z(res) })
function z(res){ console.log(res); }

Short answer: No, this code won't cause a memory leak.

Let's break down why:

  • The instance of X is temporary: When you run new X(...) without assigning the result to a variable, that instance doesn't have any persistent references pointing to it. Once the constructor finishes executing, the JavaScript garbage collector (GC) will mark this instance for cleanup—along with its reference to socketObject—since nothing else needs it.
  • socketObject is held by a top-level variable, but that's not a leak: The socketObject variable you declared at the top keeps a reference to the {hello:'world'} object, but this is intentional and expected. If you later no longer need this object, you can set socketObject = null and the GC will reclaim it. This isn't a leak—it's just normal variable scoping.
  • The callback function doesn't leave lingering references: The callback you pass to X's constructor is executed synchronously inside the constructor. Once it finishes running (and calls z(res)), there are no remaining references to this callback, so it gets cleaned up too.

When would this cause a leak?

A memory leak would only happen if:

  • You stored the instance of X in a long-lived variable (like a global object or a module-level cache) and forgot to remove it when it's no longer needed.
  • The socketObject was attached to a persistent object (like a global event emitter) that never gets cleaned up, keeping the object alive indefinitely.

But in your current code, none of these scenarios are present.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:31:01