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.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With