Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript new keyword and memory management

Tags:

Coming from C++ it is hard grained into my mind that everytime I call new I call delete. In JavaScript I find myself calling new occasionally in my code but (hoping) the garbage collection functionality in the browser will take care of the mess for me.

I don't like this - is there a delete method in JavaScript and is how I use it different from in C++?

Thanks.

like image 659
Konrad Avatar asked Mar 08 '10 16:03

Konrad


People also ask

Does JavaScript have memory management?

Some high-level languages, such as JavaScript, utilize a form of automatic memory management known as garbage collection (GC). The purpose of a garbage collector is to monitor memory allocation and determine when a block of allocated memory is no longer needed and reclaim it.

How do you do memory management in JavaScript?

Unlike low-level languages like C, JavaScript automatically allocates memory when objects are created and frees it when not in use anymore (garbage collection). C has memory-management techniques like malloc() and free().

Can JavaScript cause memory leak?

Memory management is often neglected by developers due to misconceptions of automatic memory allocation by JavaScript engines, leading to memory leaks and, ultimately, poor performance. In this article, we'll explore memory management, types of memory leaks, and hunting memory leaks in JavaScript using Chrome DevTools.


2 Answers

var component = new Component(); component = null; // delete this at next garbage collection 
like image 163
MBO Avatar answered Sep 25 '22 09:09

MBO


Incidentally, the "new" keyword isn't really necessary in javascript, and has nothing (directly) to do with allocating memory. All "new" does is pass a new, empty object called "this" (this = {}) as a hidden argument to the function.

var MyClass = function(){     // fresh empty object "this" gets passed to function     // when you use the "new" keyword      this.method = function(){} }  var myInstance = new MyClass(); 

Javascript can get kind of hairy with nested closures and multiple "this" variables floating around in different scopes. I prefer to do it this way:

var MyNoNewClass = function(){     // I find this more explicit and less confusing     var self = {}     self.method = function(){}     return self; }  var myNoNewInstance = MyNoNewClass() 
like image 24
morgancodes Avatar answered Sep 26 '22 09:09

morgancodes