var是可选的吗?

myObj = 1;

和?

var myObj = 1;

我发现他们都工作从我的测试,我假设var是可选的。对吗?


当前回答

I just found the answer from a forum referred by one of my colleague. If you declare a variable outside a function, it's always global. No matter if you use var keyword or not. But, if you declare the variable inside a function, it has a big difference. Inside a function, if you declare the variable using var keyword, it will be local, but if you declare the variable without var keyword, it will be global. It can overwrite your previously declared variables. - See more at: http://forum.webdeveloperszone.com/question/what-is-the-difference-between-using-var-keyword-or-not-using-var-during-variable-declaration/#sthash.xNnLrwc3.dpuf

其他回答

它们不一样。

未声明的变量(没有var)被视为全局对象的属性。(通常是窗口对象,除非你在with块中)

用var声明的变量是正常的局部变量,在声明它们的函数之外是不可见的。(注意Javascript没有块作用域)

更新:ECMAScript 2015

let是在ECMAScript 2015中引入的,具有块作用域。

撇开范围不谈,它们可以用不同的方式使用。

console.out(var myObj=1);
//SyntaxError: Unexpected token var
console.out(myObj=1);
//1

语句和表达式

不,这不是“必需的”,但如果你不这样做,可能会导致重大问题。不使用var定义变量,将该变量置于其所在代码部分的作用域内。如果不这样做,那么它就不包含在该作用域中,并且可以覆盖先前定义的在函数作用域之外的同名变量。

看看这个Fiddle: http://jsfiddle.net/GWr6Z/2/

function doMe(){

a = "123"; // will be global
var b = "321"; // local to doMe
alert("a:"+a+"  --  b:"+b);

b = "something else"; // still local (not global)
alert("a:"+a+"  --  b:"+b);

};


doMe()
alert("a:"+a+"  --  b:"+b); // `b` will not be defined, check console.log

Var是可选的。Var将变量置于局部作用域。如果一个变量在定义时没有使用var,那么它是在全局作用域中,是不可删除的。

edit

我认为不可删除的部分在特定的环境下在某个时间点是正确的。我一定是在做梦。