Wednesday, 5 October 2016

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





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



A simple example of my code:



$(function(){

var myvar = "stackoverflow";
});

$(function(){
alert(myvar);
});


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




var myvar = "stackoverflow";

$(function(){
alert(myvar);
});


Why?



Any help is appreciated! Thank you!



Answer



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



The first example doesn't work because the variable is defined within functional scope (meaning it's inaccessible from all except that function's scope, and the scope of functions defined within that parent function's scope).



As stated in the comments, this is just how JavaScript works. If this is a problem you're running into then it's probably time to rethink your architecture.



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



$(function() {

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


This way you can have distinct functions that are able to share their properties from within other within other functions, whilst also keeping the global namespace clean. Note, however, that in this example, a simple var x = 'something'; which isn't bound as a property of another function would do just as well.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...