📅  最后修改于: 2022-03-11 14:59:24.490000             🧑  作者: Mango
var vm = require('vm');
function myfn() {
console.log("MYFN");
console.log("MYFN: a="+ a);
}
var sandbox={console:console, a:42};
var ctx = new vm.createContext(sandbox);
// Evaluates the source code of myfn in the new context
// This will ensure that myfn uses the global context of 'ctx'
vm.runInContext(myfn.toString(), ctx, {filename: "TEST"});
// Retained in the context
console.log(ctx.myfn);
// Use it
vm.runInContext("function okfn() { console.log('OKFN'); console.log('OKFN: a='+a); } console.log('TEST'); console.log('TEST: a='+a);okfn(); myfn();", ctx, {filename:"TEST"});