In the following example, can someone explain why var1 is recognized and var2 is not? Why are the first and second treated as different scopes if they refer to the same event on the same DOM element?
$(document).ready(function() {
var1 = 12; // no var =global
var var2 = 24; // local
});
$(document).ready(function() {
console.log(var1); // = 12
console.log(var2); // fail
});
That's just how scoping works in JavaScript.
Without var
, it's always property assignment. The implicit object is window
.
It has nothing to do with events - which is part of the DOM, but not something that relates to JavaScript as a language.
Since you have used var var2
to declare var2
it is considered as a local variable, where as var1 is considered as a declared in the global scope.
Since javascript has functional scope, any variable declared within the functional scope will be available only within it
var2 is considered in a different scope because it is local to another function than the one it is called from, it doesn't have anything to do with the .ready
event. as in:
(function(){
var v = 1;
})();
//v outside that function is undefined. if you try to call it, it will return an undefined error
it is a matter of local / global variable .. please read more about the differences between them .. they exist in every programming language
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.