Analysis of the differences between javascript nested functions and calling external functions within functions

  • 2020-12-09 00:40:41
  • OfStack

We all know that a local variable defined in a function is always defined within the body of the declared function and its nested functions, and that there will always be an object in the scope chain of the function that points to the global object, giving the function access to the global variable.


var ga = 'global';
var func = function() {
  var la = 'local';
 return function() {
    return function()
    {
      return function()
      {
        alert(la);alert(ga);
      }
    }
 }

}
a = func();
a()()();//  The pop-up  local  and  global

Can A access local variables defined in B when the externally defined function A is called by the function B inside the body of the function? The answer is no. Revise the above example as follows


var ga = 'global';

function repeat() {
 alert(la);  
}
var func = function() {
  var la = 'local';
  alert(1);
  repeat();
  alert(2);
};

func();

The result of the above run is that only 1 pops up, and when calling repeat, the program is interrupted by an error because the undefined variable js interpreter was accessed.

The reason is that a scope chain is saved when the function is defined. The repeat function is defined externally, and there is no local variable called la in its scope. If we continue to look for la in the global scope, an error will be reported.

So there's a big difference between nesting a function and calling an external function nested inside a function.

Yesterday in response to a question https: / / www ofstack. com article / 78958 htm caused by thinking, although I understand concepts, but when 1 straight inside the function call repeat why can't access his function called a local variable, today again to turn over resources themselves with code under test for 1 times. I hope this article has helped others with the same problem.


Related articles: