Higher declaration of a variable

I doubt it is possible, but I would like to do it.

I would like to 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)doing something like

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

that does not really help, since the area aand bwould be bounded inside magicImport.

And of course,

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

not suitable as this will change the global object.

Is there a way for evalcode in a higher area?

EDIT . The goal, if not clear, is to create a function that can import the contents of the namespace without polluting the global area and without the need to place these imported objects in a new container object.

+3
5

, , , . eval. magicImport eval'd:

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

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

function magicImport(x){
    return "var a=" + x.a + ",b=" + x.b ;
}

. eval(magicImport(x)); :

for(prop in x){eval("var " + prop + "=" + x[prop]);}

 var str = "";
 for(prop in x){str + = "var " + prop + "=" + x[prop] + ";" ;}
 eval(str);
+1

. .

, , , , ? . , , , , , .

+3

, , , with:

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
    }
}

, ( ), with . , . ( ES5 ES5)

+2

, , , JavaScript. .

, . - " " . - , .

, , , , , . , , multi-assign, :

var x = { a: null, b: null };

// made up syntax here
<< x.a, x.b >> = magicFunction();

"magicFunction" - . Javascript , .

+1

This has little to do with areas; You are trying to copy properties into variables that have the same name.

However, here is my picture:

function magicImport(o) {
    for(property in o) {
        window[property] = o[property];
    }
}
0
source

Source: https://habr.com/ru/post/1784985/


All Articles