[英]Node.js: control the value of `this` when running a script with the `vm` module?
使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.