Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Temporarily change a JavaScript global variable

I'm trying to invisibly swap one library for another but only for a given scope. Here's a simplified sketch of the problem. x represents the old preexisting library, y represents the new library and $ is the global I want to affect. The goal is to have withLib successfully change $ from x to y for all the code within it's callback.

You can see with this example, I can affect the code in the outer context but not the inner. I've tried wrapping the callback() in a closure but that didn't quite do it either.

x = "1.0"
y = "2.0"
$ = x;

withLib = function(callback) {
  $ = y
  callback()
  $ = x
}

withLib(function(){
    console.log($, $ == "2.0" ? "outer success" : 'outer fail')
    someCb = function() {
        console.log($, $=="2.0" ? "inner success" : "inner fail")    
    }
})

someCb() 

// results in "outer success" and "inner fail"

I think the answer involves setting up the right kind of closure but I can't see how. Any thoughts?

like image 316
Matt Avatar asked Apr 14 '26 21:04

Matt


1 Answers

You could use an anonymous function to create a scope where $ is y:

x = "1.0"
y = "2.0"
$ = x;

(function ($) {

    console.log($, $ == "2.0" ? "outer success" : 'outer fail')
    someCb = function() {
        console.log($, $=="2.0" ? "inner success" : "inner fail")    
    }

}(y));

someCb()

Alternatively, the keyword with is generally to be avoided, but if you're set on it:

with ({'$': y}) {
    console.log($, $ == "2.0" ? "outer success" : 'outer fail')
    someCb = function() {
        console.log($, $=="2.0" ? "inner success" : "inner fail")    
    }
}
like image 116
Casey Chu Avatar answered Apr 17 '26 09:04

Casey Chu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!