使用'var'来声明变量是可选的吗? [英] Is using 'var' to declare variables optional?

查看:141
本文介绍了使用'var'来声明变量是可选的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var是可选的吗?

myObj = 1;

与?相同?

var myObj = 1;

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

I found they both work from my test, I assume var is optional. Is that right?

推荐答案

它们意味着不同的东西。
如果使用 var ,则变量在您所在的范围内(例如函数)声明。如果你不使用 var ,那么变量会在范围层中冒泡,直到遇到给定名称或全局对象的变量(窗口,如果你正在做的话)它在浏览器中),然后它附加。然后它与全局变量非常相似。但是,仍然可以使用 delete 删除它(很可能是其他人的代码也未能使用 var )。如果您在全局范围内使用 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 并且意外地将一个公共变量名绑定到全局对象。这会产生奇怪且难以调试的行为。

This is, in my opinion, one of the most dangerous issues with javascript, and should be deprecated, or at least raise warnings over warnings. The reason is, it's easy to forget var and have by accident a common variable name bound to the global object. This produces weird and difficult to debug behavior.

这篇关于使用'var'来声明变量是可选的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆