Javascript Node.js:在使用“vm”模块运行脚本时,是否控制“this”的值?

Javascript Node.js:在使用“vm”模块运行脚本时,是否控制“this”的值?,javascript,node.js,Javascript,Node.js,在使用vm模块运行脚本时,如何控制顶级此变量的值 据我所知: 使用vm.runScriptIn(新)上下文(…),this的值总是{} 使用vm.runScriptInThisContext(…),此的值始终为全局 是否可以进一步控制该值 编辑:例如,以防你不信任我: $ cat x.js var vm = require("vm"); vm.runInNewContext("console.log('this:', this)", { foo: 42, console: console }

在使用
vm
模块运行脚本时,如何控制顶级
变量的值

据我所知:

  • 使用
    vm.runScriptIn(新)上下文(…)
    ,this的值总是
    {}
  • 使用
    vm.runScriptInThisContext(…)
    ,此
    的值始终为
    全局
是否可以进一步控制该值

编辑:例如,以防你不信任我:

$ cat x.js
var vm = require("vm");
vm.runInNewContext("console.log('this:', this)", { foo: 42, console: console }));
$ node x.js
this: {}
编辑2:事实上,它看起来像是
这个
被设置为上下文,
控制台。log
只是:

$ cat x2.js
var vm = require("vm");
vm.runInNewContext([
    "console.log('this:', this)",
    "for (var key in this) console.log('this has key:', key);",
    "console.log('this.foo:', this.foo);"
].join("\n"), { foo: 42, console: console }));
$ node x2.js
this: {}
this has key: foo
this has key: console
this has key: key
this.foo: 42
根据


请注意我问题中的第一个要点:“对于
vm.runScriptIn(新)上下文(…)
,this
的值总是
{}
”哦,等等。节点的
console.log
只是在撒谎。你说得对。请参阅我的最新问题。
//this.hi in the vm becomes 'hello'
vm.runInNewContext(stuff, { hi: 'hello' });