声明Javascript变量时是否需要var? [英] Is var necessary when declaring Javascript variables?
问题描述
在javascript中创建变量时,在变量名称之前添加var必须吗?
When creating variables in javascript is adding "var" before the variable name a must?
例如代替
var message = "Hello World!"
我可以使用
message = "Hello World!"
?
我注意到像这样的脚本Google Adsense不使用var
I notice that scripts like Google Adsense don't use var
示例:
google_ad_width = 160;
google_ad_height = 600;
google_color_border = "000000";
google_color_bg = "ffffff";
推荐答案
没有 var
你创建了一个全局变量,而全局变量是一种很好的方法,可以让不同的函数覆盖其他变量(即它们使代码难以维护)。
Without the var
you create a global, and globals are a fantastic way to have different functions overwriting each others variables (i.e. they make code a pain to maintain).
使用 var
,变量的范围仅限于当前函数(及其中的任何内容 - 可以嵌套函数)。
With the var
, the scope of the variable is limited to the current function (and anything inside it — it is possible to nest functions).
Google Adsense使用全局变量,因为它将脚本分成两个不同的部分(一个本地和一个远程)。更简洁的方法是调用远程脚本中定义的函数并将参数作为参数传递,而不是让它从全局范围中获取它们。
Google Adsense uses globals because it splits scripts into two distinct parts (one local and one remote). A cleaner approach would be to call a function defined in the remote script and pass the parameters as arguments instead of having it pick them up from the global scope.
现代JS应该用编写禁止自动全局变量的严格模式(更喜欢在顶层显式声明它们,从而防止变量名称被拼写时意外的全局变量)。
Modern JS should be written in strict mode which bans automatic globals (preferring to explicitly declare them at the top level instead, thus prevent accidental globals when a variable name is typoed).
这篇关于声明Javascript变量时是否需要var?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!