0

Is it possible to 'pass the surrounding scope' to a function defined outside of the scope?

I was trying to make my angular js directives easier to read, and I was wondering if passing the surrounding scope was possible in Javascript. I would like a to have access to the local variable:

var a, b;

a = function() {
  return console.log('local = ', local);
};

b = function() {
  var local;
  local = 1;
  return a();
};

b();
Zabba
  • 64,285
  • 47
  • 179
  • 207
  • If the variable is defined in the outer scope, `linkedFn` will have access to it, not seeing a variable called `$rootScope` anywhere in this code though, just a string ... ? – Damon Nov 05 '16 at 21:54
  • @Damon, that was angular specific, my bad. I have fixed the example to use pure JS. – Zabba Nov 05 '16 at 21:58
  • there's no `linkFn` or `$rootScope` in the code you've provided ... in the code you've provided it looks like you want function a to have access to var local that is declared inside function b. there is no "surrounding" scope - except the global scope, so perhaps you want var local to be `window.local` or simply `local` with no preceding `var` when "declared" in function b. But this is all a guess as your text and code seem to be unconnected - alternatively pass `local` as an argument to function a and have function a accept an argument, call it local – Jaromanda X Nov 05 '16 at 23:44
  • declare `local` in the outermost scope in which it needs to be used (move the `var local` up a level) – Damon Nov 06 '16 at 00:05
  • @JaromandaX, sorry about that. Fixed. – Zabba Nov 06 '16 at 08:16

0 Answers0