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

A programming language is said to have First-class functions when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable.

Example | Assign a function to a variable

JavaScript

const foo = function() {
   console.log("foobar");
}
// Invoke it using the variable
foo();

We assigned an Anonymous Function in a Variable, then we used that variable to invoke the function by adding parentheses () at the end.

Even if your function was named, you can use the variable name to invoke it. Naming it will be helpful when debugging your code. But it won't affect the way we invoke it.

Example | Pass a function as an Argument

JavaScript

function sayHello() {
   return "Hello, ";
}
function greeting(helloMessage, name) {
  console.log(helloMessage() + name);
}
// Pass `sayHello` as an argument to `greeting` function
greeting(sayHello, "JavaScript!");

We are passing our sayHello() function as an argument to the greeting() function, this explains how we are treating the function as a value.

The function that we pass as an argument to another function, is called a Callback function. sayHello is a Callback function.

Example | Return a function

JavaScript

function sayHello() {
   return function() {
      console.log("Hello!");
   }
}

In this example; We need to return a function from another function - We can return a function because we treated function in JavaScript as a value.

A function that returns a function is called a Higher-Order Function.

Back to our example; Now, we need to invoke sayHello function and its returned Anonymous Function. To do so, we have two ways:

1- Using a variable

const sayHello = function() {
   return function() {
      console.log("Hello!");
   }
}
const myFunc = sayHello();
myFunc();

This way, it returns the Hello! message.

You have to use another variable. If you invoked sayHello directly, it would return the function itself without invoking its returned function.

2- Using double parentheses

function sayHello() {
   return function() {
      console.log("Hello!");
   }
}
sayHello()();

We are using double parentheses ()() to invoke the returned function as well.

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

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

发布评论

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

词条统计

浏览:110 次

字数:4071

最后编辑:7年前

编辑次数:0 次

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