I think I am missing very important thing about javascript
var gl = 10
$(document).ready(function() {
var obj = {}
obj.test = function() {
gl++
var lc = gl
function y() {
alert('local = ' + lc)
}
(function() {
var k = lc + 1
$('#button').click(function() {
alert('local anonymous = ' + k)
y()
})
})();
}
obj.test()
$('#button').off()
obj.test()
})
In the scenario above I have defined an object 'obj' and created a method 'test' for this object. Inside the method I have a local function 'y()' that is used by the 'click' event attached to the button. Also the click event is being attached in the anonymous function.
Then I am calling 'test()', unsubscribing 'click' event from the button and calling 'test()' once again. In a result I receive local=12 and local anonymous=13 that is expected.
However I don't understand what javascript does in memory, especially to function 'y()' and anonymous function on each of these steps.
My specific questions are below however I would be very thankful if you can explain the whole flow.
So when I have dettached all the events referencing the first 'obj.test()'. In this case I guess it's only 'click' event. Will javascript destroy 'obj.test()' scope and all functions including anonymous function scope? Do I need to care about something else?
My use case: I am creating the dynamic page loading with different page behaviors so I wanted to separate javascript for each page in the global objects methods and once the new page is loaded, i wanted to detach all the events for the previous page and call the behavior function. But suddenly I realized that I don't really understand how javascript works and potentially there can be really huge memory leaks with this approach. :--)
Many Thanks!