In Nodejs inside we want to use JS to execute JS, probably have these several ways:
1.runInThisContext
let's look at the code and output:
var vm = require (' VM '), var localvar=1;globalvar = 0;var script = Vm.createscript (' Globalvar + = 1;localvar=3 ', ' THIS.VM '); f or (var i = 0; i <; i + = 1) {Script.runinthiscontext ();} Console.log (Globalvar); Console.log (LocalVar); Console.log (Global.localvar);
Code output:
100013
From here we can see that Runinthiscontext cannot access the local scope, but can access the Golbal (Nodejs global scope), so it changes globalvar to 1000, while the local localvarl= 3 is equivalent to declaring a Localvar variable in the global scope and setting it to 3. The Localvar in the local scope continues to be 1.
2.runInNewContext
Let's look at the code and output again:
var vm = require (' VM '); var localvar=1;globalvar = 0;var sandbox = {sanboxvar:0}; var scriptnew=vm.createscript (' Sanboxvar + = 1;globalvar=4;var x=2; ', ' new.vm '); for (var i = 0; i <; i + = 1) { Scriptnew.runinnewcontext (sandbox);} Console.log (Sandbox.sanboxvar); Console.log (Sandbox.globalvar); Console.log (sandbox.x); Console.log (Globalvar);
Code output:
1000420
we see that runinnewcontext executes code entirely within a new scope, that is, it cannot access the local scope or the global scope, but can get some execution results by passing in a sandbox, such as ' sanboxvar + = 1; Globalvar=4;var x=2; ', either the Sanboxvar attribute that was passed in the sandbox, or the variable that was directly assigned by Globalvar, or the new and assigned variable x, is finally set to the Sanbox property.
3.eval
Finally, let's look at the eval code:
var Localvar=1;globalvar = 0;eval (' globalvar=3;localvar=2 '); Console.log (Globalvar); Console.log (LocalVar);
Code output
32
indicates that eval can access both the local scope and global scope, and the code above actually follows:
var Localvar=1;globalvar = 0;globalvar=3;localvar=2;console.log (Globalvar); Console.log (LocalVar);
This code is exactly the same as the direct execution of JS.
All right, here we are, basically, to understand the similarities and differences in the execution of code with Runinthiscontext,runinnewcontext,eval three ways, you can choose to use according to your own needs:
Scan the following QR code image Select the QR code in the "Recognition chart" concerned about the Royal Park code Aberdeen public Number:
Introduction to several methods of executing JavaScript code dynamically