Javascript (一):Functions As First-Class Things
2015-01-12
The term “first-class” means that something is just a value. A first-class function is one that can go anywhere that any other value can go—there are few to no restrictions. A number in JavaScript is surely a first-class thing, and therefore a first-class function has a similar nature.
术语“first-class”仅表示一个数值,基础类Function可以出现“数值”能出现的任何地方(几乎没有限制)。number确实基础类在javascript中,因此基本类Function有相似的特性:
a number can be stored in a variable and so can a function
var fortytwo = function() { return 42 };
a number can be stored in an object field and so can a function:
var fortytwos = [42, function() { return 42 }];
a number can be stored in an object field and so can a function:
var fortytwos = {number: 42, fun: function() { return 42 }};
a number can be created as needed and so can a function:
42 + (function() { return 42 })(); //=> 84
a number can be passed to a function and so can a function:
function weirdAdd(n, f) { return n + f() };
weirdAdd(42, function() { return 42 }); //=> 84
- a number can be returned from a function and so can a function:
return 42; return function() { return 42 };