destroy a function in javascript (jquery)

ben picture ben · Oct 30, 2009 · Viewed 40.5k times · Source

Is there anyone who knows how to destroy a javascript (jquery) function? I'm using jquery "selectable" and a function call "edit" is fired on selectable "stop" event.

Inside this "edit" function I have nested switch functions with a lot of "click" events and I have many functions within each "click" event. My problem is, every time I fire the "selectable" functions and events inside the function "edit" is fired again but the previous functions and events still exist. What i do now is to unbind every event in the function "edit" on selectable "start" even.

Is this a memory leak problem? and is there a way to "destroy" functions in javascript? i have tried to declare the function to null when the function ends but this does not work. functions and events inside it still exist.

anyone have a clue?

demo page here --> http://dreamerscorp.com/test/test01/javascript_destory_test.html

edit 2009/10/31 :) thanks a lot for your helps, your comments are very useful to me, thanks again!!!

Answer

Christian C. Salvadó picture Christian C. Salvadó · Oct 30, 2009

You can try to nullify the function, or override it assigning an anonymous function that does nothing:

myFunction = null;
// or 
myFunction = function () {};

You can also do it within the function itself:

var autoDestroy = function () {
  autoDestroy = null;
  //...
  return 1;
};

autoDestroy(); // returns 1
autoDestroy(); // TypeError: autoDestroy is not a function