javascript object remove - javascript

Please excuse my question if it doesnt make much sense.
I am using javascript to create a dom element
to do that i create an object ( obj ={}) and fill out the properties as i go, one of which is the dom element to be created. once the element is created and appended to the document i do not need the object to occupy any space in the memory so i was thinking i should remove it.
how would i go about doing that?
thank you

The object's going to exist in memory as soon as it's in the DOM, and the obj property that holds it is really holding a reference to it, not a copy. So as far as I know, the memory required to keep the reference as a property of obj should be negligible. In which case I wouldn't worry about removing it at all.

here is how:
my_var = null;
//or remove it
delete my_var;

if you define you object as locale like
var obj ={}
it will be automatically undefined at the end of the function.

Related

Right way to free memory in JavaScript

Being a C developer, I feel the urgent need to free memory as accurately as possible. But after reading some posts about memory management in JavaScript I still have some questions about that topic. As far as I understand, there is a garbage collector that will automatically free the memory when an object isn't referenced anymore and the GC can find the time. So an object that is held in a local variable is very likely to be freed when the variable goes out of scope.
Let's assume I have some custom elements (tab control, data table, inputs etc.). The classes of those custom elements have member variables where several data for the specific element is stored. Also event listeners can be attached to the elements the custom element consists of.
Let's say I have following html markup:
<my-tabbar>
<my-tab id="myTab">
<my-input></input>
<my-dataTable></my-dataTable>
</my-tab>
</my-tabbar>
Now I want to remove <my-tab>. Is it sufficient to just do
var element = document.getElementById ("myTab");
element.parentNode.removeChild (element);
element = null;
Or do I have to dereference every object of the child elements and remove their event listeners?
Setting an object to null makes it an empty object. Once the object is out of scope, the GC (when it runs) will clear it up. Setting local objects to null won't do you any good.
Example:
function whatever()
{
var something = null;
console.log( typeof( something ) );
}
whatever();
Output:
"object"
For the removal of a child node, please see this:
Does removeChild really delete the element?
Source(s):
https://www.w3schools.com/js/js_datatypes.asp
It is sufficient to remove the element. You don't even have to set the variable to null afterwards – you can trust the JS engine to free the memory when it goes out of scope.

(jQuery) can't append the same object multiple times

I can understand the purpose of clone() method when appending a copy element like this:
$aObject = $('.className').clone();
$aObject.removeAttr('id');
$('#add-line').click(function() {
$('#container').append( $aObject.clone());
});
But what I don't understand is, if I get rid of the clone method, just using
$('#container').append( $aObject);
I should still be able to add multiple same object to the container, but it seems like I can only add the aObject once? can't we add same object many times on purpose just like an array of same objects?
When you assign an object to a variable in JavaScript, you aren’t actually assigning the object value stored in memory – rather a reference that points to the object’s location in memory.
So, when you declare $aObject, you have now stored a reference to a particular object. When you append it, it behaves as you would expect, appending the object that you are referencing. When you try to do the same thing again, it is referring to the same object that now already exists in the DOM and simply takes that object and re-appends it (what Scott Marcus meant when he said it acts as move).
If you clone it first, then you are referencing an entirely different object, which can be appended in addition to any objects you've already appended.

How to correctly dereference then delete a JavaScript Object?

I would like to know the correct way to completely dereference a JavaScript Object from memory. To ensure it's deletion without it dangling in memory, and that the garbage collector removes the object.
When I looked and this question Deleting Objects in JavaScript. It was explained that if you delete all the references of object, the GC will remove it from memory. I want to know how do I go about removing references from an object that has both methods and properties.
Suppose you have and object that was created by using function, and the object has both methods and properties. Say it looks something like this:
function myObject(x, y) {
this.x = x;
this.y = y;
this.myMethod = function() {
// method code
}
}
var myInstance = new myObject(24, 42) // How to remove this completely?
Note: This is an example, I understand you can use prototype for methods.
I know I can't just say delete myInstance. So in this case to completely delete the object will I need to call delete on all it's properties, and then call delete on the instance, like so?
delete myInstance.x;
delete myInstance.y;
delete myInstance; // I'm not sure if this is necessary.
Would this work? Or do I need to also delete it's methods (and if so how)?
Or perhaps there is a better and simpler way to do this?
Javascript is a garbage collected language. It will clean up an object ONLY when there is no other code that has a reference to it. Those other references need to either go out of scope (and not be held by a closure) or you can set those other variables to something else so they don't point at your object. When there are no other variables with a reference to your object, it will be automatically taken care of by the garbage collector, including any properties it has (assuming none of those properties are themselves objects that something has a reference to - but even then the host object would be cleaned up and only the object in the property would continue to live on).
You cannot delete an object any other way in Javascript.
So, to remove the object created by this:
var myInstance = new myObject(24, 42) // How to remove this completely?
Just clear myInstance like this:
myInstance = null;
You don't need to manually delete the properties from myInstance at all. If nobody has a reference to the mother object and none of the properties are objects that someone has a reference to, then the garbage collector will just clean everything up for you.
The delete operator is primarily for removing properties from an object when you want the mother object to remain (e.g. when you just want to remove a property).

Javascript is changing variable that needs only to be referenced

I'm pulling some data from a reference object changing it around for what I need, but for some reason my code is also changing the object i'm referencing..
var obj = {name:"list of things", list:[{name:"thing", 1},{name:"other thing", 2}]};
function doStuff () {
var ref = obj;
for(var p=0;p<ref.list.length;p++){
ref.list.splice(1,1);
}
return ref;
}
For some reason where I'm using this structure in my code, its changing 'obj' as well as 'ref'. can't seem to figure it out
The obj in your example is not an object, it is a reference to an object that lives somewhere in memory. This is why when you do ref=obj, you get another reference to the same object, so changing the object ref references is the same as changing the object obj references.
What you want to do is clone your object, so you end up with two different objects. There are some good answers regarding cloning on StackOverflow and the whole web for that matter. Feel free to use any of those.
JavaScript assignes by reference. You would need to do a deep copy in order to clone an object.
See: http://webdevwonders.com/deep-copy-javascript-objects/

Accessing Object's Data Via Another Variable Name

It's super late and my mind is blanking right now, but let's say I have variable filename and it's storing the name of another variable marker. The variable marker is an array and contains the object & property position: new google.maps.LatLng(42.2550,-114.3221).
I've been stupidly trying to access it via filename.position which of course returns undefined, since it's searching the literal filename for a 'position' property that does not exist.
But how could I pull marker.position by using filename? Is there some nifty jQuery trick for, uh, 'resolving' a variable to its contents? I'm brain fried. I know I've done this before.
If it's possible in your script, you can store the data not just in variable, but in a property of some object (usually it's more convenient to use global one).
For example
var myObj = {};
myObj.marker = new google.maps.LatLng(42.2550,-114.3221); // or anything else
Then you will be able to get this property using a variable like this:
myObj[filename].position
In this case i would also recomment to check for myObj[filename] existance using typeof structure, just to make sure such property exists in myObj.
if (typeof myObj[filename] !== "undefined") {
// do something
}
As apsillers noted, you could use global window object for this as well. But if your marker variable was defined inside some other function (i.e. not global), you won't be able to access it with window.marker or window[filename] as it will be out of scope.
Second way is to use eval() function which i'd strongly recommend to avoid.
Try this :
window[filename].position;

Categories

Resources