Javascript function scope and calling from onclick

javascript, scope

Solution

There is no "scope of the button". What happens is that you're assigning the event listener from a scope where the inner function is visible, and that's all that matters in JavaScript. Scope in JS is about where functions are declared.

In your example:

$("#b").click(function() { changeColor() });

the function `changeColor` is available via closure inside the anonymous function, because it's declared in an outer scope. When you define a nested function, all variables and functions from the parent functions will be available inside it. So when the element is clicked and the anonymous function is called, it still has a reference to `changeColor`, and is able to call it.

You could also set the event handler without using a closure, like this:

$("#b").click(changeColor);

As I said, the important thing is that `changeColor` is in scope when you reference it (not when it's actually called, in this case, by the browser).

Problem

With JavasScript, say there is an `innerFunction()` defined within an `outerFunction()`. If you attempt to call the `innerFunction()`, outside of the `outerFunction()`, there will be an error as it is not defined within the scope. However, if while in the `outerFunction()`, you assign the `innerFunction()` to an event, say a click event, for some outside element, like a `button`, then the `innerFunction()` can be called from that scope of the button, whatever it may be. So why are you able to make this second call to `innerFunction()` froma different scope. I have a working example: http://jsfiddle.net/rcmoore38/gPrMk/ The initial `changeColor()` call does not work, but when `changeColor()` is assigned to the `button`, it can be called via the button. Thank you!

Original source

Related problems