U
U
user_of_toster2020-11-20 13:35:37
JavaScript
user_of_toster, 2020-11-20 13:35:37

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

According to the documentation, vm.runInNewContext returns the result of the last statement. That is, in f I got a function. The same as importing it from another module.

Question: why is f(api) executing a function in the vm context and not in an external script? After all, runInNewContext has already worked in the isolated scope and returned the result to the original scope. Essentially I imported a function from another script. RunInNewContext did not start again when calling f(api)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan Lopatin, 2020-11-22
@user_of_toster

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 globalThisas well.
Actually, this is the essence of execution in the context - to replace globalThis. There are no other ways. By the way, globalThisit 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 question

Ask a Question

731 491 924 answers to any question