user278064
user278064

Reputation: 10170

javascript outer scope question

It is possible to access ther oute scope of a function? I will explain better.

I've a function, from which I want to acccess its calling function scope.

function called() {
    // i want to access the calling outer function scope
}

function calling() {
    called();
}

obviusly called() function could be called by a lot of calling functions, and called() has to know time to time which function has called him,` and access its scope variables and functions.

Upvotes: 2

Views: 521

Answers (5)

Mrchief
Mrchief

Reputation: 76208

Depending on what you want to do, there might be better ways to do it, but if absoultely have to resort to it, you may find that out via Function.caller:

function myFunc() {
   if (myFunc.caller == null) {
      return ("The function was called from the top!");
   } else
      return ("This function's caller was " + myFunc.caller);
}

Do note that its not part of the standards, even though some major browsers and IE7 support it.

Also, you cannot access the caller functions scope or variables. Its usability is limited to finding out who called you (helpful for logging or tracing).

Upvotes: -1

JoshNaro
JoshNaro

Reputation: 2097

function called(outterScope) {
  // outterScope is what you want
  x = outterScope.declaredVariable;
  outterScope.declaredFunction();
}

function calling() {
  this.declaredVariable = 0;
  this.declaredFunction = function() { // do something };

  var _self = this;
  called(_self);
}

Upvotes: 1

Marek Sebera
Marek Sebera

Reputation: 40621

No,

if you need to use variables from scope of calling code block (example function)
you have to pass them in arguments

or you can create object and access properties in Object scope (via this.param_name)

Upvotes: 0

Quentin
Quentin

Reputation: 943217

No, that isn't possible.

To access a variable from two functions you need to either:

Declare it in a shared scope

var the_variable;
function called() {
    // i want to access the calling outer function scope
}

function calling() {
    called();
}

Pass it as an argument

function called(passed_variable) {
    return passed_variable;
}

function calling() {
    var some_variable;
    some_variable = called(some_variable);
}

Upvotes: 5

Domenic
Domenic

Reputation: 112817

You should pass any relevant information into called() as parameters:

function called(x, y, z) {
}

function calling() {
   var x = getX();
   var y = computeY();
   var z = retrieveZ();

   called(x, y, z);
}

If you expect called to do different things, and receive different contextual information, depending on who calls it, you should probably make it multiple separate functions.

Upvotes: 2

Related Questions