Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a variable higher up the scope chain

I doubt this is possible, but I'd like to give it a shot.

I'd like write a function that introduces new variables into the scope of its caller.

The goal is to do something like this:

(function() {
    var x = {a: 5, b:6};
    console.log(typeof a, typeof b); // prints: undefined undefined
    magicImport(x);
    console.log(a, b); // prints: 5 6
})();

// Variables are not in global scope
console.log(typeof a, typeof b); // prints: undefined undefined

If magicImport(x) does something like

eval("var a = x.a; var b = x.b;");

that doesn't really help, since the scope of a and b will be limited to inside magicImport.

And of course

eval("a = x.a; b = x.b;");

is no good since that will modify the global object.

Is there any way to eval code within a higher scope?

EDIT: The goal, in case it isn't clear, is to create function that can import the contents of a namespace without polluting the global scope, and without necessarily having to place those imported objects into a new container object.

like image 862
kpozin Avatar asked Jul 11 '26 21:07

kpozin


2 Answers

Don't do this. Unless you want to end up in a maintainance nightmare.

If I call a function I want to know what side effects it has, what if the the imported stuff changes? I will break everything. I can hardly imagine any need for such magic driven, unmaintainable code, if you really need to import stuff, return a object and use its properties, but don't do scoping magic, since this won't work with closures or other good features of the language.

like image 195
Ivo Wetzel Avatar answered Jul 14 '26 12:07

Ivo Wetzel


I'm not sure if this is what you want, but you could just use the with statement:

function() {
    var x = {a: 5, b:6};
    console.log(typeof a, typeof b); // prints: undefined undefined
    with(x) {
        console.log(a, b); // prints: 5 6
    }
}

Anyway, since this will modify the such called scope chain (pushing all propertys upfront), any other call within a with statement will become slower. This is one reason why it's not recommendable to use it. (deprecated in ES5 ES5 strict-mode anyway)

like image 40
jAndy Avatar answered Jul 14 '26 11:07

jAndy



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!