Reputation: 1184
I'm having trouble understanding jQuery variable scope.
var myVar;
function getMyVar() {
myVar = 'test';
}
$(window).load(function() {
getMyVar();
});
alert(myVar);
This code will alert 'undefined' and I need it to show 'test' and I want to understand my scope issues here.
Upvotes: 1
Views: 175
Reputation: 76238
Scoping is not limited to jQuery. Its how javascript defines scope is what rules here. jQuery is a library built on top of javascript.
Having said that, you're declaring a global variable which is accessible to everyone. However, the assignment happens after the DOM has completed loading. While the alert statement runs immediately.
If you move the alert inside of .load
after call to getMyVar()
, you'll see right value being output.
Upvotes: 1
Reputation: 82933
It's not a scope issue.
alert
is getting executed even before window.load
event is triggered which is where the variable myVar is assigned the value 'test'.
As per MDN Docs:
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
Upvotes: 3
Reputation: 18557
it's not a scope issue.
alert(myVar);
gets run before getMyVar();
Upvotes: 0
Reputation: 375814
The problem is that getMyVar isn't called until the window is loaded, while the alert is executed immediately. So the alert happens before the variable is defined. It isn't about scope, it's about the asynchronous execution of window load functions.
Upvotes: 2