javascript global variable with 'var' and

2020-02-05 07:37发布

问题:

This question already has answers here:
Closed 8 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 code examples I see over the internet use

var globalVar = something;
globalVar = something;

What's the difference?

回答1:

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.



回答2:

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.



回答3:

Outside of any function in a browser, there is no difference between using var or not with respect to scope. In both of your examples, globalVar is a member of window.

Generally, it's good practice not to have these sorts of variables, so that the global namespace doesn't become cluttered.