0

I am looking at some of my older code and I can see this, which really confuses me. Code is simplified and located inside a function (object).

$('#element')
.on('mousedown', function(e){

        var mouseX = e.pageX;

        $('body').on('mousemove', function(e){
            mouseX = e.pageX;
        });

        timer = setInterval(function(){
            console.log(mouseX);
        }, 100);
})
.on('mouseup mouseleave', function(){
    $('body').off('mousemove');
});

I needed that mouseX to be up do date when every interval fired, so back then, when my programming understanding was a bit sketchy, I simply thought, great, let's update that variable inside another event (mousemove).

Now looking at it I think - how does that local variable get updated in another scope, that is created independently and furthermore is then successfully used in completely different (interval) scope, that is also created independently?!

The code works(mouseX is correct), and it is not creating a "member" variable in parent function/object.

Can someone enlighten me a bit please.

deceze
  • 510,633
  • 85
  • 743
  • 889
Lukáš Řádek
  • 1,273
  • 1
  • 11
  • 23
  • "*how the f*ck gets that local variable updated in another scope*" the scope is *inner* to the function, so it still has access to the same variable the same way `setInterval(function(){ console.log(mouseX); }, 100)` accesses it. – VLAZ Oct 14 '19 at 18:12
  • The variable is in scope and visible to those nested functions; that's how JavaScript works. The variable is in the *closure* of each nested anonymous function. – Pointy Oct 14 '19 at 18:12
  • agreed that it is nested, but by my intuition, that scope should be long gone, when mousemove or interval fires :-) – Lukáš Řádek Oct 15 '19 at 07:17

1 Answers1

2

This is as a result of a concept called "Clousre"

...a closure gives you access to an outer function’s scope from an inner function... - MDN.

The mouseX variable was declared in a function whose scope is top-level to the callBack function given to the mousemove event listener and the setInterval callBack function, because of this, they can both access the mouseX variable.

You can read more on Closures here.

Tunmee
  • 2,483
  • 1
  • 7
  • 13