gpt4 book ai didi

javascript - function() 和 new Function() 之间的区别

转载 作者:行者123 更新时间:2023-12-02 14:39:34 24 4
gpt4 key购买 nike

在互联网上搜索时,我发现了两种编写 JavaScript 函数的方法。

其中一个是Function()构造函数

var myFunction = new Function("a", "b", "return a * b");

var x = myFunction(4, 3);

第二个是简单的定义函数

var myFunction = function (a, b) {return a * b};

var x = myFunction(4, 3);

当我使用上述两种方法时,我发现这两种方法没有区别。

这两个之间有什么区别吗?或者使用函数构造函数有什么用吗?

最佳答案

Object-Oriented JavaScript - Second Edition: When using the Function() constructor, you pass the parameter names first (as strings) and then the source code for the body of the function (again as a string). The JavaScript engine needs to evaluate the source code you pass and create the new function for you. This source code evaluation suffers from the same drawbacks as the eval() function, so defining functions using the Function() constructor should be avoided when possible.

 var first = new Function(
'a, b, c, d',
'return arguments;'
);

first(1, 2, 3, 4); // [1, 2, 3, 4]

var second = new Function(
'a, b, c',
'd',
'return arguments;'
);

second(1, 2, 3, 4); // [1, 2, 3, 4]

var third = new Function(
'a',
'b',
'c',
'd',
'return arguments;'
);

third(1, 2, 3, 4); // [1, 2, 3, 4]

Best practice: Do not use the Function() constructor. As with eval() and setTimeout(), always try to stay away from passing JavaScript code as a string.

有什么区别?请参阅@Greg 的answer

关于javascript - function() 和 new Function() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37131030/

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