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 sc开发者_如何学Goope issues here.
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.
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.
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.
it's not a scope issue.
alert(myVar);
gets run before getMyVar();
精彩评论