开发者

javascript outer scope question

开发者 https://www.devze.com 2023-04-01 19:06 出处:网络
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.

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();
}

obvius开发者_高级运维ly 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.


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);
}


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.


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);
}


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)


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号