Basically, I want to organize my code better by creating function definitions wherever I can. When I try to create a new function outside the current scope and return that, it will say x
and y
are not defined.
I know it's definitely something to do with scoping. Is there anything I can do to organize my code like in the 2nd code paragraph below? Or do I have to declare my functions in the right scope.
# Works
function RandomFunction() {
x = 1;
y = 1;
marker.addEventListener('click', function(x, y) {
return function() {
console.log(x+y);
}
}
}
# Not working
function RandomFunction() {
x = 1;
y = 1;
marker.addEventListener('click', function(x, y) {
return add;
}
}
function add() {
console.log(x+y);
}