声明 Javascript 变量时是否需要 var?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3892696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:31:28  来源:igfitidea点击:

Is var necessary when declaring Javascript variables?

javascriptvariables

提问by V777

Possible Duplicate:
Javascript: is using 'var' to declare variables optional?

可能的重复:
Javascript:是否使用“var”来声明可选的变量?

When creating variables in javascript is adding "var" before the variable name a must?

在javascript中创建变量时必须在变量名前添加“var”吗?

For example instead of

例如代替

var message = "Hello World!"

can I use

我可以用吗

message = "Hello World!"

?

?

I notice that scripts like Google Adsense don't use var

我注意到像 Google Adsense 这样的脚本不使用 var

Example:

例子:

google_ad_width = 160;
google_ad_height = 600;
google_color_border = "000000";
google_color_bg = "ffffff";

回答by Quentin

If you don't declare a variable (explicitly creating it in the current scope) using var, letor constthen (in non-strict mode) you create an implicit global.

如果您不使用var,letconst(在非严格模式下)声明变量(在当前范围内显式创建它),您将创建一个隐式全局变量。

Globals are a fantastic way to have different functions overwriting each other's variables (i.e. they make code a pain to maintain).

全局变量是让不同函数覆盖彼此变量的绝妙方法(即它们使代码难以维护)。

If you use var, the scope of the variable is limited to the current function (and anything inside it — it is possible to nest functions).

如果使用var,则变量的范围仅限于当前函数(以及其中的任何内容 - 可以嵌套函数)。

(constand letscope constants and variables to the current block instead of the function, this usually makes variables even easier to manage than vardoes.)

constlet作用域常量和变量到当前块而不是函数,这通常使变量比以前更容易管理var。)

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.

Google Adsense 使用全局变量是因为它将脚本分成两个不同的部分(一个本地和一个远程)。一种更简洁的方法是调用远程脚本中定义的函数并将参数作为参数传递,而不是让它从全局范围内获取它们。



Modern JS should be written in strict modewhich bans implicit globals (preferring to explicitly declare them at the top level instead, thus prevent accidental globals when a variable name is typoed).

现代 JS 应该以严格模式编写,禁止隐式全局变量(宁愿在顶层显式声明它们,从而防止在输入变量名称时意外使用全局变量)。

回答by Tim Down

Yes, you should always use var.

是的,您应该始终使用var.

Not using varhas two major drawbacks:

不使用var有两个主要缺点:

  • Accessing a variable within a function that is not defined within that function will cause the interpreter to look up the scope chain for a variable with that name until either it find one or it gets to the global object (accessible in browsers via window) where it will create a property. This global property is now available everywhere, potentially causing confusion and hard-to-detect bugs;
  • Accessing an undeclared variable will cause an error in ECMAScript 5 strict mode.
  • 访问函数中未在该函数中定义的变量将导致解释器查找具有该名称的变量的作用域链,直到找到一个变量或它到达全局对象(在浏览器中可通过 访问window)创建一个属性。这个全局属性现在随处可用,可能会导致混淆和难以检测的错误;
  • 在 ECMAScript 5 严格模式下访问未声明的变量会导致错误。

Also, not using varfor global variable is not exactly the same as using var: when using var, the property it creates on the global object has the internal DontDeleteattribute, which is not the case without var:

此外,不var用于全局变量与 using 不完全相同var:当 using 时var,它在全局对象上创建的属性具有内部DontDelete属性,如果没有,则情况并非如此var

// Next line works in any ECMAScript environment. In browsers, you can
// just use the window object.
var globalObj = (function() { return this; })();

var x = 1;
delete globalObj.x;
alert(x); // Alerts 1, x could not be deleted

y = 2;
delete globalObj.y;
alert(y); // Error, y is undefined

回答by Matthew Vines

From http://www.updrift.com/article/to-var-or-not-to-var-my-javascript

来自http://www.updrift.com/article/to-var-or-not-to-var-my-javascript

  1. For global variables, it doesn't matter, but you may want to use it for consistency.
  2. Always try to use ‘var' to declare variables in local functions. It makes sure you're using a local copy of the variable instead of another variable of the same name in a different scope.
  1. 对于全局变量,这无关紧要,但您可能希望使用它来保持一致性。
  2. 始终尝试使用 'var' 在局部函数中声明变量。它确保您使用的是变量的本地副本,而不是不同作用域中的另一个同名变量。

For example, the two similar functions here have very different effects:

比如这里两个相似的函数,效果就大不相同:

var myvar = 0;
function affectsGlobalVar(i){
   myvar = i;
}
function doesNotAffectGlobalVar(i){
   var myvar = i;
}

回答by MatTheCat

Without var a variable is defined as global.

没有 var 变量被定义为全局变量。

回答by Gary Willoughby

For the unenlightened like myself, JavaScript basically has two scopes for variables: global and local. Variables assigned outside of a function are global, and variables assigned inside of a function, using the var keyword, are local (not rocket surgery). However, if you leave the var keyword off, it assigns a global variable, regardless of where it's declared.

对于像我这样没有启蒙的人来说,JavaScript 基本上有两个变量作用域:全局和局部。在函数外部分配的变量是全局的,而在函数内部使用 var 关键字分配的变量是局部的(不是火箭手术)。但是,如果关闭 var 关键字,它会分配一个全局变量,而不管它在哪里声明。

From: http://opensoul.org/2008/9/4/the-importance-of-var-in-javascript

来自:http: //opensoul.org/2008/9/4/the-importance-of-var-in-javascript

回答by Babak Naffas

When adding Google AdSense to your page, you're linking a number of javascript files. The variables are defined in there.

将 Google AdSense 添加到您的网页时,您将链接许多 javascript 文件。变量在那里定义。

http://pagead2.googlesyndication.com/pagead/show_ads.jsshould be one of the script references in your page.

http://pagead2.googlesyndication.com/pagead/show_ads.js应该是您页面中的脚本引用之一。