簡體   English   中英

Node.js:使用“ vm”模塊運行腳本時,控制“ this”的值嗎?

[英]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

根據vm模塊文檔 ..

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM