0đ
JavaScript does not have memory leaks (in the traditional sense) because it has automatic garbage collection. The JS interpreter records a reference count for every object (including numbers, strings, etc.). When the reference count hits 0, the object will be deleted (usually using a âmark-and-sweepâ algorithm).
So, in your example, exampleData.name is actually a reference to some object (number, string, JS object, etc.), and when you enter exampleData.name = {}, two things happen (letâs assume exampleData.name was originally equal to the string âoldnameâ):
- â{}â creates a new object with a single reference count (exampleData.name now points to it)
- The string object âoldnameâ now has a reference count of 0, because its only reference, exampleData.name, not points to something else. Now, the next time the garbage collector runs, exampleData.name will be deleted.
Having said that, it is possible to unintentionally waste memory (though not a memory leak in the traditional sense) in certain JavaScript scenarios, like the following closure:
function wastefulFunc(){
var giantObj = {};
///fill giantObj up with thousands of entries
function closureFunc(){}
return closureFunc;
}
var waste = wastefulFunc();
Even though it doesnât look like it, giantObj will be kept around for as long as the âwasteâ var exists, because the scope created by closureFunc sets the reference count of giantObj to 1.
As for a âtrueâ memory leak, consider a language like C++, which doesnât have automatic garbage collection:
void leakFunc(){ Foo* f = new Foo; }
The code above creates a pointer, f, which points to an explicitly allocated Foo object. As soon as the function finishes, however, the variable f will be destroyed, but we have no way of referencing the memory it pointed to. Since C++ does not have automatic garbage collection, the allocated memory that f pointed to will forever be marked as allocated, and we CANNOT get free it, because we have lost any way of referencing it! Therefore, the memory has âleakedâ out of the pool of memory available to our program.
- [Vuejs]-How to create pagination as child component that reusable in VueJS
- [Vuejs]-Hide an item when is deleted with this.$http.delete()