Despite the fact that what you want is achievable, I do not recommend using global variables at all and encourage you to rethink your architecture. Global variables are hard to maintain and can cause errors.
var
always creates a variable that has a function scope, so it means it's accessible in the function that it was declared in and all the functions inside that function (unless redefined inside them). If you want to make it global no matter where it is, you have a few options:
Direct assignment to non-existing variable
In case you run your code in non-strict mode, just drop the var
. This will cause the lookup of variable line
and since it's not declared in any context, it will assign it as a global variable. Example:
function fn() {
line = 1;
}
fn();
console.log(line); //1
Two drawbacks though:
- If you ran this code in a strict mode it would cause a
ReferenceError
- If there was a variable with same name in one of the outside functions, it would be overwritten and no global variable would be created
Example:
function outer() {
var line;
function inner {
line = 8; //won't work because there is variable line in some outer context
}
inner();
}
outer();
console.log(line); //undefined
Assignment to global object
In every JS execution environment there is something called the global object. If you assign a property to it, you could use it as a global variable (except that it's not a variable - the difference is subtle, but there is). For example:
function fn() {
window.line = 1;
}
fn();
console.log(line); //1;
This also has some drawbacks:
- the global object is not necessarily hiding under
window
variable. In Node it's global
and it may vary in other execution environments
- in case there's a variable with name
window
(or global
) declared on the way, it will override that variable (similar to drawback #2 from previous point)
- you could use
this
to access the global object, but only in non-strict mode and only if this
wasn't explicitly set (see rules for computing this
value)
Indirect eval/new Function
Indirect eval
and new Function
are always executed as if they were declared directly inside the global scope. Although not elegant and error-prone (you code using strings), they do not suffer from previous drawbacks - work even in strict mode, no matter what variables have been declared on the way and independently from the execution environment. It's simple as that:
'use strict';
function fn() {
//choose one of the following:
//indirect eval:
(0, eval)('line=1');
//or new Function
new Function('line=1')();
}
fn();
console.log(line); //1. Works even in strict mode
You may ask "why this weird (0, eval)(...)
instead of just eval
? That's what called indirect eval, and you can find more info about that under this SO answer
As you see, it is possible. But again, global variables make your code hard to maintain. You should limit the scope of line
variable to the area it will be actually used.