A way to construct Functions with custom scopes?
Bergi
a.d.bergi at web.de
Wed Jun 10 18:24:23 UTC 2020
Hi!
It's a bit unclear to me what problem you are trying to solve, but you
can already construct closures with custom scopes using the `Function`
constructor:
```js
function makeFunction(name, args, body, scope, values) {
if (typeof args == "string")
values = scope, scope = body, body = args, args = [];
if (!Array.isArray(scope) || !Array.isArray(values)) {
if (typeof scope == "object") {
values = Object.values(scope);
scope = Obect.keys(scope);
} else {
values = [];
scope = [];
}
}
return Function(scope, `
function ${name}(${args.join(", ")}) {
${body}
}
return ${name};
`)(...values);
};
const foo = makeFunction("foo", [], "console.log(x)", {x: 10})
foo(); // logs 10
```
kind regards,
Bergi
More information about the es-discuss
mailing list