Replies: 2 comments 1 reply
-
I guess you can either prefix references to const compartment = new Compartment({ __options__: true, globals: { this: { value: 1 }}});
console.log(compartment.evaluate('globalThis.this.value')) // 1 or wrap evaluated code in a function call whose receiver is the desired object const compartment = new Compartment({ __options__: true, globals: { this: { value: 1 }}});
const wrapSourceForThis = expr => {
const functionBody = `return(\n${expr}\n);`;
Function(functionBody); // check validity
return `Reflect.apply(function(){${functionBody}},globalThis.this,[])`;
};
console.log(compartment.evaluate(wrapSourceForThis('this.value'))) // 1 And in in either case, you'll want to decide on appropriate behavior for recursive evaluation. |
Beta Was this translation helpful? Give feedback.
-
The keyword To achieve the effect that you are looking for, you can use a compartment’s unique const c = new Compartment();
console.log(new c.globalThis.Function('return this.value').call({ value: 1 })); |
Beta Was this translation helpful? Give feedback.
-
We're migrating from another Javascript-embedded language, JEXL, where we use
this
to refer to a particular constant object value.e.g. Our user can use an expression such as
this.value + 1
to increment a value.How do I set the value of
this
in a compartment? Settingthis
on the global object doesn't seem to work:Beta Was this translation helpful? Give feedback.
All reactions