Every variable properly declared will always have a local scope to the current function.
Since you're using the var
statement properly, your x
and y
variables are local to your anonymous function.
If you want to be able to access those variables from your onMouseClickFunction
function, you should declare them outside your click
event handler. You'll still have access to them from within the click handler, since that function itself is declared within the onMouseClickFunction
function.
This is known as JavaScript's scope chain lookup: if a variable you're using has not been declared within the local scope, JavaScript will look for it in the scope just above the current one (which in the case of your anonymous function is the outer onMouseClickFunction
). If it's not declared there either, it'll keep on looking all the way up the scope, till it reaches the global scope.
If the variable is not found anywhere through the scope chain, it'll be declared as a new variables in the global scope. That's why it's imperative to always declare your variables with a var
statement, as you've done.