0
var x = 1;
function fn() {
 console.log(x);
}
function show(f){
 var x = 2;
 f();
}
show(fn);

fn() function should have access to its outer execution context show(), which x is define as 2.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 4
    JavaScript has lexical scope, not dynamic scope. It considers the source code location, not the call stack. – Bergi Nov 19 '19 at 00:36
  • Btw, your example is unnecessarily complicated. You could just have called `fn()` from within `show`, no need to pass it as an argument `f`. – Bergi Nov 19 '19 at 00:38

1 Answers1

0

No. f is bound with the context as it was when f was defined, that is, when x = 1. If you want x = 2, you need to define fn inside of the show function.

Travis Webb
  • 14,688
  • 7
  • 55
  • 109