8

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.

Isaac Reason
  • 266
  • 2
  • 9
  • Worrying about the GC or "memory usage" is silly in this case, as the assignment *does not create a new object*. Thus the only 'wasted' object is the object containing the values that will be copied over *and* this assumes there are no aggressive optimizations performed. (Where 'wasted' is such a small value that even mentioning a chance of 'waste' is *incorrect, biased, and misleading*). – user2864740 Jun 08 '17 at 22:32
  • If you don't know the names of the object properties, how would you use them as variable names?! – Bergi Jun 08 '17 at 23:22
  • @user2864740 This function will be called many times with many different objects. If I don't use delete operator properties will fill my global scope (kind of memory leak). If I use it operation will take much time (Even more than eval()). I'm just looking for the best option. – Isaac Reason Jun 17 '17 at 18:25

1 Answers1

3

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?

amiramw
  • 506
  • 2
  • 10