我在阅读 Airbnb JavaScript 风格指南时遇到了 this提到以下功能的部分:
var subtract = Function('a', 'b', 'return a - b');
我在 Chrome 调试器控制台中测试了这个,方法是输入上面的行,然后输入:
subtract(7,3)
它返回了 4
。我很惊讶它真的有效。
风格指南提到这样做不是一个好主意,但它让我开始思考这个函数语法。我从未见过没有主体的函数返回正确的结果。
这是如何/为什么起作用的,它存在了多长时间,使用它的指南/最佳实践是什么?
最佳答案
这将使用 Function
object 创建一个函数而不是“正常的” function
语法。注意大写字母“F”。
var subtract = Function('a', 'b', 'return a - b');
意味着你定义了一个带有参数a
和b
的函数,函数体return a - b
。相当于
var subtract = function (a, b) { return a - b; };
通常,您希望在调用这样的构造函数时使用 new
,但没有它也能正常工作;它只是有点难读(对人类而言)。
来自Mozilla Developer Network解释:
The
Function
constructor creates a newFunction
object. In JavaScript every function is actually aFunction
object.Syntax
new Function ([arg1[, arg2[, ...argN]],] functionBody)
Parameters
arg1
,arg2
, ...argN
Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
functionBody
A string containing the JavaScript statements comprising the function definition....
Invoking the
Function
constructor as a function (without using thenew
operator) has the same effect as invoking it as a constructor.
关于javascript - Function 类是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37381360/