This is an alternative method (written in ES6):
(new Function(...Object.keys(context), codeYouWantToExecute))(...Object.values(context));
Credits to Jonas Wilms for the answer.
Here is my explanation, since I did not initially understand how it worked:
let example = new Function('a', 'b', 'return a+ b')
is the same as creating the function and assigning it to example
:
function(a,b) {
return a + b
}
After that, you can call example
like this: example(2,6)
which returns 8.
But let's say you don't want to assign the function created by new Function
to a variable and you want to immediately call it instead.
Then you can just do this:
new Function('a', 'b', 'return a+ b')(2,6)
The code snippet at the top of this post is essentially doing the same thing. It uses the spread operator to pass in the keys of the context
object like this:
new Function(key1, key2, key3... lastkey, codeYouWantToExecute)
. It then calls the newly created function and passes the values that correspond to each key with the spread operator.
Lastly, here is the answer compiled to ES5:
(new (Function.bind.apply(Function, [void 0].concat(Object.keys(context), [codeYouWantToExecute])))()).apply(void 0, Object.values(context));