1

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 of this is always {}.
  • With vm.runScriptInThisContext(…), the value of this is always GLOBAL.

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

1 Answer 1

0

As per the documentation for vm module..

//this.hi in the vm becomes 'hello'
vm.runInNewContext(stuff, { hi: 'hello' });
2
  • Please note the first bullet point in my question: “With vm.runScriptIn(New)Context(…), the value of this is always {}.” Jan 15, 2012 at 23:05
  • OH WAIT. Node's console.log is just lying. You are correct. See my updated question. Jan 15, 2012 at 23:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.