什么是一等函数
What is a first class function
看答案Show answer
一句话:「一等」说的是函数和普通值地位相同—— 能赋给变量、能当参数传、能当返回值、 能放进数组和对象。
这是语言的性质,不是某个函数的性质。说「JavaScript 有一等函数」是对的, 说「这是一个一等函数」就怪了。
为什么重要:一等函数是回调、高阶函数、闭包、 函数式编程的前提。arr.map(fn) 之所以能写, 就是因为 fn 可以当参数。
会追问:下面三题连着问 —— 一等(能当值)→ 一阶(不碰函数)→ 高阶(收或返函数)。先把这三个词分清。
In one line: “first class” means functions have the same standing as any other value — you can assign one to a variable, pass one as an argument, return one, and store them in arrays and objects.
This is a property of the language, not of a particular function. “JavaScript has first class functions” is correct; “this is a first class function” sounds wrong.
Why it matters: first class functions are the precondition for callbacks, higher order functions, closures and functional programming. You can only write arr.map(fn) because fn can be an argument in the first place.
Follow-up: the next three come as a set — first class (works as a value) → first order (touches no functions) → higher order (takes or returns a function). Get those three terms apart first.