1

In Javascript, it is said that functions are executed using the scope that was in effect when the function was defined. It has nothing to do with the scope in effect when the function is called.

What exactly does it mean? Could someone please explain with simple examples.

copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • 1
    may this link helps http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – rab Mar 15 '13 at 12:31

2 Answers2

2

The output of the following is A because foo is defined in the scope of function a, so the variable data that it uses is the one that is also defined in the scope of function a.

It doesn't output B even though the function was called in the scope of function b where data = "B".

<div id="output"></div>
<script>
  var data = "global";

  function a() {
    var data = "A";
    function foo() {
       document.getElementById('output').innerHTML = data;
    }
    return foo;
  }

  function b() {
    var data = "B";
    var func = a();
    func();
  }

  b();
</script>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0
// Global variables are on every scope chain
var global = 'global'

// Function variables are only on a function's scope chain
function bar() {
  var fn = 'fn';

  // foo called from here where fn is avaialble as a local variable
  foo(); // undefined

  return function() {
    alert(fn)
  }
}


function foo() {
  // foo can access global because it's on its scope chain
  alert(global);

  // Can't access fn because it's on bar's scope chain
  // so returns undefined
  alert(typeof fn);    
}

// the function returned by bar has access to fn
var f = bar(); // global

f(); // fn
RobG
  • 142,382
  • 31
  • 172
  • 209