var是可选的吗?

myObj = 1;

和?

var myObj = 1;

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


当前回答

They mean different things. If you use var the variable is declared within the scope you are in (e.g. of the function). If you don't use var, the variable bubbles up through the layers of scope until it encounters a variable by the given name or the global object (window, if you are doing it in the browser), where it then attaches. It is then very similar to a global variable. However, it can still be deleted with delete (most likely by someone else's code who also failed to use var). If you use var in the global scope, the variable is truly global and cannot be deleted.

在我看来,这是javascript中最危险的问题之一,应该弃用,或者至少在警告中提出警告。原因是,很容易忘记var,并偶然地将一个通用变量名绑定到全局对象。这会产生奇怪且难以调试的行为。

其他回答

They mean different things. If you use var the variable is declared within the scope you are in (e.g. of the function). If you don't use var, the variable bubbles up through the layers of scope until it encounters a variable by the given name or the global object (window, if you are doing it in the browser), where it then attaches. It is then very similar to a global variable. However, it can still be deleted with delete (most likely by someone else's code who also failed to use var). If you use var in the global scope, the variable is truly global and cannot be deleted.

在我看来,这是javascript中最危险的问题之一,应该弃用,或者至少在警告中提出警告。原因是,很容易忘记var,并偶然地将一个通用变量名绑定到全局对象。这会产生奇怪且难以调试的行为。

想想今天在StackOverflow上被问到的这个问题:

简单的Javascript问题

上面的场景是一个很好的测试和一个实际的例子…… 开发人员在他的一个变量中使用了JavaScript函数的名称。

代码有什么问题? 该代码仅在用户第一次单击按钮时起作用。

解决方案是什么? 在变量名之前添加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

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

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

语句和表达式

不,它们不相等。

myObj = 1;您正在使用一个全局变量。

后一种声明在您使用的范围内创建一个局部变量。

尝试下面的代码来理解差异:

external = 5;
function firsttry() {
  var external = 6;
  alert("first Try: " + external);
}

function secondtry() {
  external = 7;
  alert("second Try: " + external);
}

alert(external); // Prints 5
firsttry(); // Prints 6
alert(external); // Prints 5
secondtry(); // Prints 7
alert(external); // Prints 7

第二个函数改变全局变量“external”的值,但第一个函数不会。