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.
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.
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().
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.
var component = new Component(); component = null; // delete this at next garbage collection
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With