How to get variables from outside, inside a function in jQuery?

I am trying to figure out how I can get variables from outside in a function, inside a function in jQuery, but I get Uncaught ReferenceError: myvar is not defined . Is there any way to do this?

A simple example of my code:

 $(function(){ var myvar = "stackoverflow"; }); $(function(){ alert(myvar); }); 

But when I define a variable outside the function, it works:

 var myvar = "stackoverflow"; $(function(){ alert(myvar); }); 

Why?

Any help is appreciated! Thanks!

+6
source share
4 answers

The reason the second example works is because you define myvar as a global variable (accessible from anywhere).

The first example does not work because the variable is defined within the functional scope (which means that it is not available to everyone except that scope of the function and the scope of functions defined within this parent function).

As stated in the comments, this is how JavaScript works. If this is a problem you are facing, then you will probably need to rethink your architecture.

One common pattern is to define shared variables as properties of parent objects or functions. For instance:

 $(function() { var funcOne = function() { this.sharedVal = 'stack overflow'; }; var funcTwo = function() { console.log(funcOne.sharedVal); }; }); 

Thus, you can have different functions that can share their properties from another in other functions, while maintaining a global namespace. Note, however, that in this example, simple var x = 'something'; , which is not bound as a property of another function, will do the same.

+8
source

In its second example, myvar is in the global scope, while the first is contained in a function.

You can make it global, though:

 $(function(){ window.myvar = "stackoverflow"; }); $(function(){ alert(myvar); }); 

(suppose this is in the browser)

+6
source

This is due to the volume of the variable. A variable defined in $ (function () has a scope within this function. The contest here describes the scope. The specified variable, defined outside the function, has a global scope and is defined in the window object.

The internal function of the area.

 $(function(){ var myvar = "stackoverflow"; }); // myvar is not accessible here. 

The area inside the window object.

 $(function(){ window.myvar = "stackoverflow"; }); // myvar is accessible here. 
+3
source

When you declare a variable inside a function. Its scope is limited only by this function (in the case of one of your scenarios).

To access them everywhere outside a function, you need to declare it a global variable. This is the second case.

+1
source

All Articles