2

Throwing exception in constructor can lead to memory leaks: source 1, source 2. This is true for some OO languages like C++, C#, Java. I am wondering if JavaScript is susceptible to the same memory-leak issue?

To illustrate, I have this JS code:

Widget = function(){
    console.log("Widget constructor");
};

Foo = function(){
    console.log("Foo constructor");
    this.w = new Widget();
    throw new Error();
};

Foo.prototype.dispose = function() {
    delete this.w;
};

var f = new Foo;
f.dispose();

Obviously I'll the dispose() will never get called, but in that case I am very curious what is the fate of the f.w object? Does it remain in memory and cannot be cleared in any way (causing memory leaks)? Or perhaps the garbage collector is smart enough and recognizes that it is not referenced anywhere and actually disposes it? How is this handled by different JS engines? If it is true then how to avoid it?

Community
  • 1
  • 1
Maciej Sz
  • 11,151
  • 7
  • 40
  • 56

0 Answers0