开发者

Javascript anonymous functions

I have the following code:

for (var i=0; i < 20; i++) {
    var itemButton = $('<button />').click(function(){ alert('Hello'); }).append('Hello');
    $('#container').append(itemButton);                            
}

Where i create lots of buttons each with a onclick function. Then i clear the #container using $('#shopSearchTopBar').empty(); and create the buttons again.

My question is: Is this a possible memory leak? Does Javascript frees the memory us开发者_StackOverflowed for those anonymous functions i created the first time when i call the .empty() method on the #container or the memory gets freed an i can safely add those 20 new buttons each with his own new anonymous function?


Those functions are stored in jQuery.cache.

As long as you use jQuery methods like .empty(), that data will be cleaned up for all affected elements.

If you did something like this:

document.getElementById('container').innerHTML = '';

Then you'd likely have a pretty nasty memory leak because the connection between each element and jQuery.cache would be severed and that data (and likely more) would be sitting orphaned in the cache.

Stick to the jQuery methods when removing/overwriting content, and you'll be fine.

Even when doing this:

$('#container').html('');

...jQuery will clean up that data for affected elements.


If all the anonymous function does is show an alert, then I'd define the function outside the loop, and reference it by name. That way, it'll only get created once, instead of 20 times.

var clickHandler = function(){ alert('Hello'); };

for (var i=0; i < 20; i++) {
    var itemButton = $('<button />').click(clickHandler).append('Hello');
    $('#container').append(itemButton);                            
}

It's different if it makes use of closures, but that doesn't seem to be the case here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜