简体   繁体   中英

what is the difference in variable delaration here?

I am picking up maintenance of a project and reading code:
I see two methods of variable declaration. Can someone explain what the difference between the first and second line means?

To me, I am reading that in javascript, the var keyword is optional. in the first line, they have declared two new variables and initialized them. In the second line, they have declared two new varialbes but not have initialized them. Should I take anything more from this?

aURL = ""; msgNb = 1;
var mode, param, counter;

Unless all these variables are inside a function they're all globals, the first two are assignments which I would guess because they were previously declared, otherwise it may be shortened to

var aURL = '', 
    msgNb = 1, 
    mode, 
    param, 
    counter;

The unassigned ones have an undefined value by default.

You should always use the var keyword to keep the variable within the same function scope and not force it to become an implicit global, otherwise you could run into issues with duplicate variable naming and assignment.

如果您不使用var那么您将使用(或创建)来自“父”范围的变量,如果在任何范围内都找不到本地变量,则一直使用全局变量。

This is not a "jquery" issue per say but rather a JavaScript issue. A variable without the "var" keyword has global scope, ie, it is visible from all methods, objects, etc... A var is only visible within its specific scope.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM