开发者

javascript global variable with 'var' and without 'var' [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Difference between using var and not using var in JavaScript

I understand that I should always use 'var' to define a local variable in a function.

When I define a global function, what's the difference between using 'var' ?

Some of co开发者_如何学Gode examples I see over the internet use

var globalVar = something;
globalVar = something;

What's the difference?


Well, the difference is that technically, a simple assignment as globalVar = 'something'; doesn't declare a variable, that assignment will just create a property on the global object, and the fact that the global object is the last object in the scope chain, makes it resolvable.

Another difference is the way the binding is made, the variables are bound as "non-deletable" properties of its environment record, for example:

var global1 = 'foo';
delete this.global1; // false

global2 = 'bar';
delete this.global2; // true

I would strongly encourage you to always use the var statement, your code for example will break under ECMAScript 5 Strict Mode, assignments to undeclared identifiers are disallowed to avoid implicit globals.


Short: There is no difference in the global context**.

Long: The Variable object for the global context is the global context itself. That is why we can just access global variables and methods within a function-, or eval context. However, the var statement just makes sure you're defining a variable in the current context, so it makes no difference by omitting that in the global context. Exception: ES5 strict mode will probably throw an error when it sees a declaration without var.


** the only difference is, that var will declare a variable without definition in the current (execution) context. This happens at js parse time, so the engine knows that there is a variable with that name available in the context. Omitting var will end up in a direct property access from the global object.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜