andrew
andrew

Reputation: 9593

what's the correct way to destroy a javascript function?

I'm not too familiar with object orientated Javascript but lets say I have a function which I instantiated.. ?

Is that the correct terminology?

The function contains an XMLHttpRequest with an attached event listener, what would be the correct way to dispose the function?

function foo() {
    var self = this;
    self.message = "received response";
    self.url = 'someUrl';
    self.req = new XMLHttpRequest();
    self.req.open("POST", self.url, true);
    self.req.onload = function () {
        console.log(self.message); // Unable to get property 'message' of 
        // undefined or null reference
    };
    self.req.send();
    self = null;
}

var foo = new foo();

I realize this is not how I should abort an XMLHttpRequest but its just an example, the question is how should I cleanly destroy a function and all that it spawned or created?

Edit

To Clarify, my confusion is with self.req.onload and how it can even exist when self = null? my thought would be that self.req no longer exists and therefore its events too but this is obviously not the case

Upvotes: 2

Views: 1211

Answers (2)

Hampus
Hampus

Reputation: 2799

I would write you example like this:

function foo () {
  var message = "received response";
  var url = 'someUrl';
  var req = new XMLHttpRequest();
  req.open("POST", url, true);
  req.onload = function () {
    console.log(message);
  };
  req.send();
}

// No need to instantiate foo, just call it when you want to make your request
// No need for foo to "remember" variables.

foo();

Upvotes: 1

Bergi
Bergi

Reputation: 665555

Yes, JavaScript functions are objects, and therefore they are instantiated. Function declarations create a function when the scope is entered, function expressions do when they are evaluated.

However, in JavaScript you don't dispose objects. You just let them go out of scope (remove all references to them), and the garbage collector will take care of them. For example, when you foo.req.abort() the request, or the response arrives, and foo.req.onload is no longer accessible, then your listener function will be garbage collected.

Upvotes: 4

Related Questions