- Mastering JavaScript Functional Programming
- Federico Kereki
- 287字
- 2021-07-02 22:41:07
Functions as First Class Objects
Saying that functions are first class objects (also: first class citizens) means that you can do everything with functions, that you can do with other objects. For example, you can store a function in a variable, you can pass it to a function, you can print it out, and so on. This is really the key to doing FP: we will often be passing functions as parameters (to other functions) or returning a function as the result of a function call.
If you have been doing async Ajax calls, you have already been using this feature: a callback is a function that will be called after the Ajax call finishes and is passed as a parameter. Using jQuery, you could write something like:
$.get("some/url", someData, function(result, status) {
// check status, and do something
// with the result
});
The $.get() function receives a callback function as a parameter, and calls it after the result is obtained.
This is better solved, in a more modern way, by using promises or async/await, but for, but for the sake of our example, the older way is enough. We'll be getting back to promises, though, in section Building Better Containers, of chapter 12, Building Better Containers – Functional Data Types, when we discuss Monads; in particular, see section Unexpected Monads: Promises.
Since functions can be stored in variables, you could also write:
var doSomething = function(result, status) {
// check status, and do something
// with the result
};
$.get("some/url", someData, doSomething);
We'll be seeing more examples of this in Chapter 6, Producing Functions – Higher–Order Functions, when we consider Higher–Order Functions.
- Reporting with Visual Studio and Crystal Reports
- 深入淺出Prometheus:原理、應用、源碼與拓展詳解
- 琢石成器:Windows環境下32位匯編語言程序設計
- VMware虛擬化技術
- Java零基礎實戰
- 零基礎看圖學ScratchJr:少兒趣味編程(全彩大字版)
- ASP.NET求職寶典
- Mastering Embedded Linux Programming
- Tableau Dashboard Cookbook
- Implementing Microsoft Dynamics NAV(Third Edition)
- Python應用開發技術
- 機器人ROS開發實踐
- Java程序員面試筆試真題庫
- HTML5+CSS3從入門到精通(微課精編版)
- ArcGIS Pro 2.x Cookbook