gpt4 book ai didi

javascript - Node.js:使用 `this` 模块运行脚本时控制 `vm` 的值?

转载 作者:太空宇宙 更新时间:2023-11-04 02:43:57 25 4
gpt4 key购买 nike

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

据我所知:

  • 对于 vm.runScriptIn(New)Context(…)this 的值始终为 {}
  • 使用 vm.runScriptInThisContext(…) 时,this 的值始终为 GLOBAL

是否可以进一步控制该值?

编辑:例如,以防万一您不信任我:

$ cat x.js
var vm = require("vm");
vm.runInNewContext("console.log('this:', this)", { foo: 42, console: console }));
$ node x.js
this: {}

编辑 2:事实上,看起来 this 设置为上下文,console.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

最佳答案

根据 documentation for vm module ..

//this.hi in the vm becomes 'hello'
vm.runInNewContext(stuff, { hi: 'hello' });

关于javascript - Node.js:使用 `this` 模块运行脚本时控制 `vm` 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8873969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com