Function - MDN Web Docs Glossary: Definitions of Web-related terms 编辑

A function is a code snippet that can be called by other code or by itself, or a variable that refers to the function. When a function is called, arguments are passed to the function as input, and the function can optionally return a value. A function in JavaScript is also an object.

A function name is an identifier included as part of a function declaration or function expression. The function name's scope depends on whether the function name is a declaration or expression.

Different types of functions

An anonymous function is a function without a function name. Only function expressions can be anonymous, function declarations must have a name:

// When used as a function expression
(function () {});
// or using the ECMAScript 2015 arrow notation
() => {};

The following terms are not used in the ECMAScript language specification, they're jargon used to refer to different types of functions.

A named function is a function with a function name:

// Function declaration
function foo() {};
// Named function expression
(function bar() {});
// or using the ECMAScript 2015 arrow notation
const foo = () => {};

An inner function is a function inside another function (square in this case). An outer function is a function containing a function (addSquares in this case):

function addSquares(a,b) {
   function square(x) {
      return x * x;
   }
   return square(a) + square(b);
};
//Using ECMAScript 2015 arrow notation
const addSquares = (a,b) => {
   const square = x => x*x;
   return square(a) + square(b);
};

A recursive function is a function that calls itself. See recursion.

function loop(x) {
   if (x >= 10)
      return;
   loop(x + 1);
};
//Using ECMAScript 2015 arrow notation
const loop = x => {
   if (x >= 10)
      return;
   loop(x + 1);
};

An Immediately Invoked Function Expressions (IIFE) is a function that is called directly after the function is loaded into the browser’s compiler. The way to identify an IIFE is by locating the extra left and right parenthesis at the end of the function’s definition.

// Declared functions can't be called immediately this way
// Error (https://en.wikipedia.org/wiki/Immediately-invoked_function_expression)
/*
function foo() {
    console.log('Hello Foo');
}();
*/

// Function expressions, named or anonymous, can be called immediately
(function foo() {
    console.log("Hello Foo");
}());

(function food() {
    console.log("Hello Food");
})();

(() => console.log('hello world'))();

If you'd like to know more about IIFEs, check out the following page on Wikipedia : Immediately Invoked Function Expression

Learn more

Technical reference

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:103 次

字数:4194

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文