gpt4 book ai didi

javascript - 使用 `new Function` 和性能问题

转载 作者:数据小太阳 更新时间:2023-10-29 05:55:22 24 4
gpt4 key购买 nike

我正在通过 AJAX 加载一个脚本文件,并运行它的内容,我正在这样做:

new Function('someargument',xhr.responseText)(somevalue);

但是,根据 MDN:

Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function and calling it within your code, because functions declared with the function statement are parsed with the rest of the code.

我真的不太明白。如果声明了一个函数,它仍然必须从文件的字符串格式进行解析,那么为什么通过 new Function 运行加载的字符串效率会更低?

这对我来说真的更像是一件好奇的事情。我能理解为什么它在循环中会很糟糕(必须重新解析相同的字符串),但是对于这样的事情我认为没有任何问题,是吗?

最佳答案

我认为他们的意思是,如果您像这样在代码中使用函数构造函数:

new Function('bar', 'console.log(bar);'));

函数体被解析两次:第一次是在加载代码时解析为字符串,第二次是在运行时构造函数时。在您的情况下,您是在解析代码后从 ajax 响应创建函数,所以这真的是完全不同的事情。

关于javascript - 使用 `new Function` 和性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16431228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com