new Function()是否返回最后一个值



如何从new Function()构造函数返回最后一个值?似乎eval()vm.Script#runInContext在默认情况下都会这样做。

我只想在浏览器中创建一个REPL(在那里我可以做一些类似2+2;的事情,它在输出中返回4(,类似eval,但没有eval的缺点(本地函数范围访问、AsyncFunction等(

您可以使用Web Worker在隔离的范围内运行一些东西。在那里,您可以安全地使用eval,而不用担心访问页面的本地范围变量。试试这样的东西:

function run() {
const code = `
self.onmessage = async (evt) => {
let result;
try {
result = await eval(evt.data);
} catch(err) {
result = 'Error: ' + err.message;
}  
self.postMessage(result);
};
`;
const blob = new Blob([code], {
type: "text/javascript"
});
const worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function(e) {
document.getElementById('out').value = e.data;
}
worker.postMessage(document.getElementById('repl').value);
}
<label for="repl">REPL:</label>
<input type="text" id="repl">
<button onclick="run()">Execute</button>
<p/>
<label for="out">Output:</label>
<input type="text" id="out" readonly>

受到这个答案的启发:(

没有办法做到这一点。

CCD_ 10不提供任何方式来访问";竣工记录";根据Function对象上的ECMAScript规范部分。

因此,如果您需要最后一个值,则必须使用eval()

最新更新