Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Convert object properties to variables inside function scope [duplicate]

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.

like image 509
Isaac Reason Avatar asked May 03 '17 07:05

Isaac Reason


People also ask

How do you overwrite an object property?

Using the spread operator to overwrite an object property We'll use the spread operator, which you can recognize by the three dots. Let's say we want the status to be true. We can use the following call. It's a super clean syntax and easy to see which value we are overwriting.

How do you copy properties from one object to another in JavaScript?

Object.assign() The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.


1 Answers

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?

like image 115
amiramw Avatar answered Oct 02 '22 17:10

amiramw