The scope of variables defined in $(function(){})

Often because there are too many function modules on a page, such as a tab page. We want to write the function of each module in a js, but in order to distinguish, we define multiple $(function(){}) in a module, the function defined in $(function(){}) What will happen to the domain? Here are a few examples

(1)$(function(){

var a=1;

})

$(function(){

alert(a);

})

At this time, an error will be reported, a is undefined, because the variable a can be valid in the defined $(function(){}), so what if we really want to define a public variable? I summed it up.

method one:

(1)$(function(){

window.a=1;

})

$(function(){

alert(a);

})

output: 1

Note: Don’t write it backwards, if it is defined in $(function(){}) below, it will also display a as undefined, because $(function(){}) is written in front of it and loaded first.

Method Two:

(2)

var a=1;

$(function(){

alert(a);

})

output: 1

The post Scope of variables defined in $(function(){}) first appeared on Lenix Blog .

This article is reprinted from https://blog.p2hp.com/archives/9139
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment