- 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.
- Practical Data Analysis Cookbook
- Functional Python Programming
- Java多線程編程實戰(zhàn)指南:設計模式篇(第2版)
- Oracle 11g從入門到精通(第2版) (軟件開發(fā)視頻大講堂)
- 數(shù)據(jù)庫原理及應用(Access版)第3版
- 垃圾回收的算法與實現(xiàn)
- HTML5+CSS3基礎開發(fā)教程(第2版)
- 概率成形編碼調制技術理論及應用
- Visual Basic程序設計上機實驗教程
- Instant PHP Web Scraping
- 深入理解Kafka:核心設計與實踐原理
- Flink核心技術:源碼剖析與特性開發(fā)
- Python數(shù)據(jù)可視化之matplotlib實踐
- Java程序設計(項目教學版)
- 小學生C++編程課堂(新手篇)