简体   繁体   中英

Access variables from anonymous JavaScript function

Is it possible to access variables within an anonymous function outside of said function?

I may be using the wrong terminology.

Using the below pseudo code, would it be possible to access var1 in another script loaded on the same page?

function(i,e){
    var var1;
    NewFunc.init = function(){
         var1 = 5; 
    };
}

Is it possible to access variables within an anonymous function outside of said function?

No, and in fact this is one of the things we use functions for: Hiding things. :-) More below about why that's not just a quirk of syntax.

Variables within a function are entirely private to that function and other functions created within it (which "close over" the variables in scope where they're created). For instance:

 function foo() { var answer = 42; function bar() { var question = "Life, the Universe, and Everything"; console.log(question, answer); // Works fine } console.log(question, answer); // Fails with a ReferenceError because // `question` is out of scope } foo(); 

bar can access foo 's answer variable because bar is created within foo . But foo cannot access bar 's question variable because foo isn't created within bar .

This means it's possible to create functions that can access and modify a private variable:

 // This is ES5 and earlier style; in ES2015+, it could be a bit more concise function foo() { var answer = 42; return { getAnswer: function() { return answer; }, setAnswer: function(value) { answer = value; } }; } var o = foo(); console.log(o.getAnswer()); // 42 o.setAnswer(67); console.log(o.getAnswer()); // 67 

Note that if we tried to replace

console.log(o.getAnswer()); // 42

with

console.log(answer);

there are two good reasons that fails:

  1. The variable is out of scope

  2. If somehow it were in scope, which answer should it refer to? We can call foo more than once, and each call creates a new answer variable, so...


Side note: It makes no difference whether the function is named or anonymous, or whether it's a normal function or one of ES2015's new "arrow" functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM