Javascript - Convert object properties to variables inside function scope
javascript, object, properties, scope, variables
Solution
Other than using the window object you have the option of using `eval`:
let scope = { property: "value" }
function fun(scope)
{
for (let p in scope)
{
if (scope.hasOwnProperty(p))
eval("var " + p + " = scope[p];");
}
console.log(property);
}
fun(scope);
See also: How do i declare and use dynamic variables in javascript?
Problem
This is what i want to achieve: ``` let scope = { property: "value" }; function fun() { //That's how I can get my variables: console.log(this.property); //And that's how I want to get them console.log(property); } fun.call(scope); ``` But of course the bind() function doesn't work like that. My idea was to do it this way: ``` let scope = { property: "value" } function fun(scope) { for (let p in scope) { if (scope.hasOwnProperty(p)) window[p] = scope[p]; } // Now it works console.log(property); } fun(scope); ``` Unfortunately by doing this variables are declared in the global scope and the Garbage Collector won't free them up after function execution. So I would have to also add something like this at the end of my function: ``` for (let p in scope) { if (scope.hasOwnProperty(p)) delete window[p]; } ``` But as we all know delete operator is pretty heavy, so I would like to omit using it. That's why I'm looking for a way to convert object properties into variables in function scope. PS: I can't use destructuring assignment because I don't know names of object properties.