javascript Window vs Var 来声明变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7082886/
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-10-25 22:54:51  来源:igfitidea点击:

Window vs Var to declare variable

javascript

提问by William Sham

Possible Duplicate:
Difference between using var and not using var in JavaScript
Should I use window.variable or var?

可能的重复:
在 JavaScript 中使用 var 和不使用 var 的区别
我应该使用 window.variable 还是 var?

I have seen two ways to declare a class in javascript.

我见过两种在 javascript 中声明类的方法。

like

喜欢

window.ABC = ....

or

或者

var ABC = ....

Is there any difference in terms of using the class/ variable?

在使用类/变量方面有什么区别吗?

回答by gn22

window.ABCscopes the ABC variable to window scope (effectively global.)

window.ABC将 ABC 变量范围限定为窗口范围(有效全局)。

var ABCscopes the ABC variable to whatever function the ABC variable resides in.

var ABC将 ABC 变量范围限定为 ABC 变量所在的任何函数。

回答by Alex Turpin

varcreates a variable for the current scope. So if you do it in a function, it won't be accessible outside of it.

var为当前作用域创建一个变量。因此,如果您在函数中执行此操作,则无法在函数外部访问它。

function foo() {
    var a = "bar";
    window.b = "bar";
}

foo();
alert(typeof a); //undefined
alert(typeof b); //string
alert(this == window); //true

回答by Dennis

window.ABC = "abc"; //Visible outside the function
var ABC = "abc"; // Not visible outside the function.

If you are outside of a function declaring variables, they are equivalent.

如果您在声明变量的函数之外,则它们是等效的。

回答by wanovak

windowmakes the variable global to the window. Unless you have a reason for doing otherwise, declare variables with var.

window使变量全局到窗口。除非您有理由不这样做,否则请使用var.

回答by Tejs

The major difference is that your data is now attached to the window object instead of just existing in memory. Otherwise, it is the same.

主要区别在于您的数据现在附加到 window 对象而不是仅存在于内存中。否则,它是一样的。