views:

17

answers:

2

I have a question in JavaScript context. I'm a little confused by this issue. The code below describes my question:

$(..).someFunction{
  var outOfScope = "OUT OF SCOPE!";

  $('somelink').click(handler);

  function handler() {
    alert(outOfScope);
  }
}

My question is: how outOfScope variable (which was defined outside the handler) is seen inside the handler?

+3  A: 

The variable outOfScope is scoped to someFunction, so it is available inside someFunction.

The function handler is inside someFunction, so the variable outOfScope is still available.

David Dorward
A: 

That´s how JavaScript works.

All variables that are defined directly inside a scope will also be available in all the scopes that are defined inside the scope.

Christian
Not quite true. Variables inside the scopes that are inside a scope are not available to the outer scope or other inner scopes. Just to be picky ;) Maybe you could put "directly inside a scope".
sje397
Thanks, fixed :)
Christian