2012-01-15 52 views
1

如何在使用vm模塊運行腳本時控制頂層this變量的值?Node.js:使用`vm`模塊運行腳本時控制`this`的值?

至於我可以告訴大家:

  • 隨着vm.runScriptIn(New)Context(…)this值總是{}
  • With 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 

回答

0

由於每documentation for vm module ..

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

請注意我的問題中的第一個要點:「使用'vm.runScriptIn(New)Context(...)','this'的值總是'{}'。」 – 2012-01-15 23:05:46

+0

OH WAIT。節點的'console.log'只是說謊而已。你是對的。看到我更新的問題。 – 2012-01-15 23:14:21