Javascript closure and risk of memory leak

I was looking for memory leaks in my javascript code again. Ater discovering some major leaks, I start looking for a minor one and find it might be a potential leak - the "hoverIntent.js" plugin. I would like to ask if this is really a leak or am I overdoing it too much?

General code outline (full code here http://cherne.net/brian/resources/jquery.hoverIntent.js ):

(function($) {
    $.fn.hoverIntent = function(f,g) {

    //...


    var track = function(ev) {
        cX = ev.pageX;
        cY = ev.pageY;
    };

    var compare = function(ev,ob) {
        //... function body
    };


    var delay = function(ev,ob) {
       //... function body
    };


    var handleHover = function(e) {
      //... function body
    };


    return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover);
    };
})(jQuery);

      

I know a lot of js plugins are written this way, but ... If I get it right every time I call hoverIntent

on my object 3 new functionality (closures) are created? Isn't this a possible memory leak (or at least a performance issue)?

Isn't it better to write like this:

(function($) {

  //create the methods only once on module init?

    var track = function(ev) {
        cX = ev.pageX;
        cY = ev.pageY;
    };

    var compare = function(ev,ob) {
        //... function body
    };


    var delay = function(ev,ob) {
       //... function body
    };


    var handleHover = function(e) {
      //... function body
    };


    $.fn.hoverIntent = function(f,g) {
            //no closures here
    return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover);

    };
})(jQuery);

      

+3


source to share


1 answer


You are correct, your second example will use less memory due to smaller closing functions. But as soon as you don't raise the event (the item is removed, etc.), They disappear again, so this is not a "leak" since the memory is not lost forever.



Also, many plugins use closures, setting the current state of an element in a variable instead of the element itself.

+2


source







All Articles