cychoi
cychoi

Reputation: 3090

Access function scope chain from a globally defined function

function globalFunc1() {
  console.log(hello);
}

function globalFunc2() {
  var hello = 'hello';
  globalFunc1(); // expected to print "hello" but `hello` is undefined instead
}

globalFunc2();

Would that be possible without passing the inner variable(s) to globalFunc1()? I am currently using the following hack to achieve what I want but it's way too hackish and inelegant.

function globalFunc2() {
  var hello = 'hello';
  eval('(' + globalFunc1.toString() + ')()');
}

Edit:

I am actually looking for some features from Javascript which are similar to Function.prototype.bind, .call or .apply to achieve what I wanted to do.

To elaborate what I am doing:

function checker() {
  if (someVar == 'some value') { 
    /* ... */
  }
}

setTimeout(function() {
  var someVar = 'some value';
  /* ... */
  checker();
}, 1000);

Upvotes: 0

Views: 38

Answers (1)

user663031
user663031

Reputation:

You could move globalFunc1 inside globalFunc2, so it has access to the latter's internal variables, but assign it to a global variable to allow it to be invoked from outside:

function globalFunc2() {

  window.globalFunc1 = function() {
    console.log(hello);
  };

  var hello = 'hello';
  globalFunc1(); // will print "hello"
}

globalFunc1(); // will print "hello"

Here, globalFunc1 is defined inside globalFunc2, and so has access to the variables in its closure, hello in this case. However, it itself is a global variable, allowing it to be accessed from outside.

In terms of how you asked the question, you can "access function scope chain from a globally defined function" if (and only if) that globally defined (perhaps one should say "declared" instead) function points to a function inside the other function's scope.

Whatever you do, do not do your eval thing. What you are essentially doing there is defining (and then immediately executing) the function by lexically copying it in. Instead of doing that, why not just write the function there to start with, as above?

Upvotes: 2

Related Questions