Function and eval can both execute snippets of javascript code, assuming that the following code needs to be executed in the window environment:

1.Function

// Assume that the current execution environment is this, i.e. Window; let content = this; let executeCode = function (str) { return new Function(str); }Copy the code

First create the current environment content, then create an executable instance through a function expression

  • Case 1: Get the current href
ConsoleStr let consoleStr = 'console.log(window.location.href)'; // Create an executable function reference let consoleRender = executecode. call(content, consoleStr); / / execution consoleRender ();Copy the code
  • Case 2: Insert a newly created div into a node
<body> // Full text root node <div id="app"></div> <script> // Create an executable string nodeStr var nodeStr = 'var node = document.createElement('div'); node.innerHTML = 'hello world'; document.querySelector('#app').appendChild(node); '// create an executable function reference let nodeRender = executecode. call(content, nodeStr); / / execution nodeRender (); </script> </body>Copy the code

2.eval

Eval can be performed directly as follows:

eval(consoleStr);
eval(nodeStr);
Copy the code

Conclusion: Function and eval can achieve the same effect when executing snippets, but Function is recommended for security reasons.