Question

So I was trying to get a handle on JavaScript's scope and looking up lots of info about it. I saw a lot of questions about people accidentally making local variables that conflicted with global ones.

But I was wondering if there was a way to change global variables despite a conflicting local variable. Like:

    var globalVariable = 6;

    var func1 = function() {
       this.func2 = function() {
          var globalVariable = 99;   
                   = 7;
       }
    };
    print(globalVariable);

Is there a way to change the global variable value despite that conflicting local variable name?

When I tried this.globalVariable = 7 to print 7 as the output, it did not work. Can anyone make clear why the this.access did not work or if there is even a way to change the global variable if there does happen to be a local of conflicting name?

Obviously it would not make sense to write code this way, but I thought I understood that the this. keyword always specified the global variable/object?

Was it helpful?

Solution

"I thought I understood that the this. keyword always specified the global variable/object?"

No. The value of this depends on how a function is called and whether the function is in strict mode.

In the browser global variables are properties of the window object, so use:

window.globalVariable = 7;

Sometimes this is equal to window, but often it is not. (I don't mean that to sound like this just gets set randomly; there is a specific set of rules that apply.)

Note that if you find yourself needing to distinguish between global variables and local variables like this you might well be using too many global variables.

OTHER TIPS

You could use window['globalVariable'] = 7;

It's not a good solution though. There really are none.

The "this" variable refers to the scope the current function has, usually, unless it was bound to something else or called/applied (.call/.apply). I'd suggest Googling function scope because it can get quite confusing.

I'm on Skype if you have any more questions (thetenfold).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top