It a general javascript question.
I am using closures a lot and want to make sure not keeping too many variables in memory.
see sample code below.
Creating 10 div and attaching click event listener.
Event listener function is using a private variable of its parent. So a closure is created.
I assume variable '_closure' will not be garbage collected.
Put a breakpoint and '_local' got no scope.
Assume its garbage collected.. right?
- function f() {
- var _local = 1;
- var _closure = 2;
- var _div;
- for (var i = 0; i < 10; i++) {
- _div = $("<div>" + i + "</div>");
- _div.on("click.test", function (i) {
- return function () {
- alert(_closure++);
- }
- }(i));
- $("body").append(_div);
- }
- }
- $(document).ready(function () {
- f();
- });
is below a better design considering performance. It creates less anonymous functions.. ?
- function f() {
- var _local = 1;
- var _closure = 2;
- var _sub = function (i) {
- return function () {
- alert(_closure+++" ---- " + i);
- }
- }
- var _div;
- for (var i = 0; i < 10; i++) {
- _div = $("<div>" + i + "</div>");
- _div.on("click.test", _sub(i));
- $("body").append(_div);
- }
- }
- $(document).ready(function () {
- f();
- });