Answer the question
In order to leave comments, you need to log in
Why does the function derived from VM.runInNewContext run in the context of the VM sandbox?
'use strict';
const vm = require('vm');
const timers = require('timers');
const events = require('events');
const context = {console};
const api = {timers, events};
globalThis.a = 3;
const code = `api => {
globalThis.a = 5;
console.log(globalThis.a); // выводит 5
};`;
const f = vm.runInNewContext(code, context)
f(api);
console.dir(f) // выводит 3
Answer the question
In order to leave comments, you need to log in
console.dir(f)
will display [Function (anonymous)]
.
Your code returns a function from vm.runInNewcontext()
. This function is closed to the context in which it was created, like any closure. No matter how many times she was called.
It's just that the context to which it is closed includes the variable globalThis
as well.
Actually, this is the essence of execution in the context - to replace globalThis
. There are no other ways. By the way, globalThis
it will be changed only for your code. Other functions will be locked to the context in which they were created. And it will no longer be possible to change their context after creation.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question