var是可选的吗?
myObj = 1;
和?
var myObj = 1;
我发现他们都工作从我的测试,我假设var是可选的。对吗?
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
其他回答
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中引入的,具有块作用域。
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,并偶然地将一个通用变量名绑定到全局对象。这会产生奇怪且难以调试的行为。
Var是可选的。Var将变量置于局部作用域。如果一个变量在定义时没有使用var,那么它是在全局作用域中,是不可删除的。
edit
我认为不可删除的部分在特定的环境下在某个时间点是正确的。我一定是在做梦。
Javascript中的var关键字是有目的的。
如果你声明一个没有var关键字的变量,就像这样:
myVar = 100;
它变成了一个全局变量,可以从脚本的任何部分访问。如果你不是故意这样做的,或者没有意识到这一点,如果你在javascript的另一个地方重复使用变量名,它会给你带来痛苦。
如果你用var关键字来声明变量,就像这样:
var myVar = 100;
它是作用域的局部({]-括号,函数,文件,取决于你把它放在哪里)。
这是一种更安全的处理变量的方法。因此,除非你是故意这样做,尽量声明变量与var关键字,而不是没有。