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
Xis temporary: When you runnew 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 tosocketObject—since nothing else needs it. socketObjectis held by a top-level variable, but that's not a leak: ThesocketObjectvariable 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 setsocketObject = nulland 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 callsz(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
Xin 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
socketObjectwas 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
相关产品推荐
相关产品推荐

