Changing a Variable Out of Scope?

15,970

Solution 1

No. No tricks or overrides. You have to plan to have both places be able to see the variable in the same scope.

The only trick I can think of regarding scope is using window in a browser to get to the global object. This can help you get to a "hidden" variable--one that's in scope but whose name has been overtaken by a local variable (or other variable closer in the scope chain).

Closures and classes can afford you some other tricks with scope, but none that allow you to override the scoping rules entirely.

Solution 2

i don't see why you would need to do that, if you need a variable that is accessible from the outside, just declare it on the outside.

now, if you are asking this just because you are trying to learn something, good for you.

var a = 0;

function blah() {
    a = 1;
    return a;
}
a = 2;

alert(blah());

Solution 3

You can return the value from the function, of course:

function blah() {
    var a=1;
    return a;
}

But I assume that's not quite what you had in mind. Because a function invocation creates a closure over local variables, it's not generally possible to modify the values once the closure is created.

Objects are somewhat different, because they're reference values.

function blah1(v) {
    setInterval(function() {
       console.log("blah1 "+v);
    }, 500);
}
function blah2(v) {
    setInterval(function() {
       console.log("blah2 "+v.a);
    }, 500);
}

var a = 1;
var b = {a: 1};
blah1(a);
blah2(b);
setInterval(function() {
   a++;
}, 2000);
setInterval(function() {
   b.a++;
}, 2000);

If you run this in an environment with a console object, you'll see that the value reported in blah2 changes after 2 seconds, but blah1 just goes on using the same value for v.

Share:
15,970
Matrym
Author by

Matrym

Updated on June 12, 2022

Comments

  • Matrym
    Matrym almost 2 years

    Is there any way to change a variable while out of scope? I know in general, you cannot, but I'm wondering if there are any tricks or overrides. For example, is there any way to make the following work:

    function blah(){
     var a = 1
    }
    a = 2;
    alert(blah());
    

    EDIT (for clarification):

    The hypothetical scenario would be modifying a variable that is used in a setInterval function which is also out of scope and in an un-editable previous javascript file. It's a pretty wacky scenario, but it's the one I intend to ask about.