Home > Web Front-end > JS Tutorial > Analysis of the difference between javascript nested functions and calling external functions within functions_javascript skills

Analysis of the difference between javascript nested functions and calling external functions within functions_javascript skills

WBOY
Release: 2016-05-16 15:16:46
Original
1351 people have browsed it

We all know that local variables defined in a function are always defined within the function body in which it is declared and its nested functions, and there will always be an object pointing to the global object in the scope chain of the function, so that Functions can access global variables.

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

}
a = func();
a()()();// 弹出 local 和 global
Copy after login

So when function A defined externally is called by function B in the function body, can A access the local variables defined in B? The answer is no, slightly modify the above example as follows

var ga = 'global';

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

func();
Copy after login

The above operation result is that only 1 pops up. When repeat is called, the js interpreter reports an error because it accesses an undefined variable and interrupts the program.

The reason is that the function saves a scope chain when it is defined. The repeat function is defined externally. There is no local variable called la in its scope. If we continue to search in the global scope, we still cannot find la, so an error will be reported. .

So there is a big difference between nested functions and nested calls to external functions within functions.

I was thinking yesterday when answering a question http://www.jb51.net/article/78958.htm. Although I understand the concept, I always wanted to call repeat inside the function. Why? I can't access the local variables of the function that calls him. I checked the reference materials again today and tested it myself with the code. I hope this article can help friends who have the same confusion.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template