0

What I am trying to work out is whether nullifying is always necessary. As I am having a few issues with Chrome. Say I have this code.

function MyClass() {}
MyClass.prototype.MyFunction = function() {
 this.data = "foo";
}
var c = new MyClass();
c.MyFunction();

Now once that function is called it should be allowed to be GC but should the end of the function have this.data = null. Should this also be standard.

asked Jan 24, 2013 at 9:58
3
  • 1
    That code will throw a TypeError. Did you mean to instantiate MyClass? Commented Jan 24, 2013 at 10:00
  • here's a helpful article: ibm.com/developerworks/library/wa-memleak Commented Jan 24, 2013 at 10:05
  • Yeah I was writing the code in here and forgot to add that. Commented Jan 25, 2013 at 8:51

1 Answer 1

1

Your code will not work. You should first create an instance of your class:

var c = new MyClass();
c.MyFunction();

because MyFunction is instance function.

Otherwise there's also delete operator (reference and an indepth analysis), that is used to remove object members (but not objects themselves). Objects can therefore be garbage collected when there's no way to reference them any more, so

c = undefined;

should convince Javascript to garbage collect this object instance and release memory resources taken by it.

It is different if your object instance is instantiated this way:

c = new MyClass();
c.MyFunction();
delete c; // success

because c is this time a member of global (window) and can therefore be deleted from it.

answered Jan 24, 2013 at 10:01
Sign up to request clarification or add additional context in comments.

5 Comments

My main issue is that I cannot remove the main class.
@Sam_Benne: Class or instance of your class?
Instance. Its a "Single Page App" So I need to keep the main instance but I can clear other smaller ones which I do.
@Sam_Benne: So what's the problem then? Why and when would you want to clear the main instance?
I haven't got a problem what I was trying to find out is whether the GC would clean out the vars that are generated in the function when it is not in use.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.