开发者

Window vs Var to declare variable [duplicate]

This question already has answers here开发者_如何转开发: Closed 11 years ago.

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.

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜