javascript - Function 类是如何工作的?

标签 javascript

我在阅读 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');

意味着你定义了一个带有参数ab的函数,函数体return a - b。相当于

var subtract = function (a, b) { return a - b; };

通常,您希望在调用这样的构造函数时使用 new,但没有它也能正常工作;它只是有点难读(对人类而言)。

来自Mozilla Developer Network解释:

The Function constructor creates a new Function object. In JavaScript every function is actually a Function 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 the new operator) has the same effect as invoking it as a constructor.

关于javascript - Function 类是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37381360/

相关文章:

javascript检测浏览器并使用特定的样式表

javascript - JQuery 单击元素外部

javascript - ng 类表达式无法解析

javascript - 在执行下一个代码之前, typescript 会等待循环完成吗?

javascript - 是否可以通过 JavaScript 触发链接(或任何元素)的点击事件?

javascript - 如何在 bing map (win8) 中使用来自 www 的图像

javascript - 在文本框中输入内容后,jquery 函数不起作用

javascript - jquery/javascript 中单选按钮取消选择的事件监听器

javascript - 浏览器 API : how to pass advanced option to script

javascript - 如何使用 Selenium 或 Poltergeist 与 javascript 弹出窗口交互?