I'm trying to understand (probably simple concepts) about JS, and I've put together the below piece of code to explain what I don't get. What I do not understand is where the name variable is stored. Is that variable now global?
(function($) {
var name = '';
$.helloWorld = function(yourName) {
name = yourName;
console.log("Hello " + yourName);
}
}(jQuery));
-
The variable is scoped to that closure, that's the point of IIFEs, to encapsulate code and not leak variables to the outer scope.elclanrs– elclanrs2013年06月11日 04:45:09 +00:00Commented Jun 11, 2013 at 4:45
-
This question is similar to: What is the scope of variables in JavaScript?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.dumbass– dumbass2024年12月26日 08:52:17 +00:00Commented Dec 26, 2024 at 8:52
2 Answers 2
The name variable is local to the outer function, because it's declared with the var keyword. The inner function is a closure that contains a reference to that variable. Here's a better example that shows this off:
(function($) {
var name = '';
$.setName = function(newName) {
name = newName;
}
$.showName = function() {
console.log("Name is: " + name);
}(jQuery));
After defining this, you can do:
$.setName("Larry");
$.showName();
$.setName("Fred");
$.showName();
5 Comments
alert(name);This should help you understand:
(function(){
var name;
var scope1;
// Here you can use scope1 and name
(function(){
var name; // <------------------------
var scope2; // |
// |
// Here you can use scope1,scope2, and name
(function(){
var name; // <------------------------------
var scope3; // |
// |
// Here you can use scope1,scope2,scope3, and name
})();
})();
})();
// Any\variable declared outside of any function scope is in the global scope.
// A variable declared here can be accessed by window.name from any scope
var name = 5;
So in this snippet, 3 scopes are created by the three functions and in the innermost you can access the variables that have unique names (scope1,scope2, and scope3) as well as the local variable name, which is a separate name from the one it the middle scope. Reusing variable names like that to prevent access to the variable in an outer scope is called shadowing.
Note that a variable that is not declared with the var keyword is auotmatically assumed to be in the global scope. It is a bad practice to declare many variables in the global scope as they can easily conflict with other scripts.