开发者

Where to use "var' in javascript programs [duplicate]

开发者 https://www.devze.com 2023-01-03 22:12 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: Difference between using var and not using var in JavaScript
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Difference between using var and not using var in JavaScript

Hello,

I am a self learned developer. Always, i write javascripts without开发者_运维问答 the var for variables. But some javascripts use var for variables.

Both worked well for me. I am bit confused by this.

Is Writing scripts with var a standard form or they used only within classes ?


var limits the scope of a variable to the function it is declared in, if you don't use var you create a global.

Globals tend to lead to code that is hard to maintain and suffers from race conditions.

Always use var unless you have a very good reason not to.


If you don't use var, the variable will be global, not limited in the scope you're in (a problem for say another variable in the global space with the same name, you just over-wrote it, probably unintentionally).

Short version: always use var to be safe.

0

精彩评论

暂无评论...
验证码 换一张
取 消