copenndthagen
copenndthagen

Reputation: 50732

JavaScript function execution scope

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?

Upvotes: 1

Views: 73

Answers (2)

RobG
RobG

Reputation: 147363

// 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

Upvotes: 0

Quentin
Quentin

Reputation: 943185

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>

Upvotes: 2

Related Questions