How can I control the value of the top-level this variable when running a script with the vm module?
As far as I can tell:
- With
vm.runScriptIn(New)Context(…), the value ofthisis always{}. - With
vm.runScriptInThisContext(…), the value ofthisis alwaysGLOBAL.
Is it possible to control that value any further?
Edit: For example, just in case you don’t trust me:
$ cat x.js
var vm = require("vm");
vm.runInNewContext("console.log('this:', this)", { foo: 42, console: console }));
$ node x.js
this: {}
Edit 2: In fact, it looks like this is set to the context, console.log just lies:
$ 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
As per the documentation for vm module..