Window vs Var to declare variable

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

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

like

window.ABC = ....

or

var ABC = ....

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


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

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


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

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

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

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

如果你在声明变量的函数之外,它们是等价的。

链接地址: http://www.djcxy.com/p/17352.html

上一篇: var关键字和无var之间的区别

下一篇: 窗口与Var来声明变量