官术网_书友最值得收藏!

Arrow functions

Arrow functions are just a shorter, more succinct way of creating an (unnamed) function. Arrow functions can be used almost everywhere a classical function can be used, except that they cannot be used as constructors. The syntax is either (parameter, anotherparameter, ...etc) => { statements } or (parameter, anotherparameter, ...etc) => expression. The first one allows you to write as much code as you want; the second is short for { return expression }. We could rewrite our earlier Ajax example as:

$.get("some/url", data, (result, status) => {
// check status, and do something
// with the result
});

A new version of the factorial code could be:

const fact2 = n => {
if (n === 0) {
return 1;
} else {
return n * fact2(n - 1);
}
};
console.log(fact2(5)); // also 120

Arrow functions are usually called anonymous functions, because of their lack of a name. If you need to refer to an arrow function, you'll have to assign it to a variable or object attribute, as we did here; otherwise, you won't be able to use it. We'll see more in section Arrow Functions of Chapter 3, Starting Out with Functions - A Core Concept.

You would probably write the latter as a one-liner -- can you see the equivalence?

const fact3 = n => (n === 0 ? 1 : n * fact3(n - 1));
console.log(fact3(5)); // again 120

With this shorter form, you don't have to write return -- it's implied. A short comment: when the arrow function has a single parameter, you can omit the parentheses around it. I usually prefer leaving them, but I've applied a JS beautifier, prettier, to the code, and it removes them. It's really up to you whether to include them or not! (For more on this tool, check out https://github.com/prettier/prettier.) By the way, my options for formatting were --print-width 75 --tab-width 4 --no-bracket-spacing.

In lambda calculus, a function as x => 2*x would be represented as λx.2*x  -- though there are syntactical differences, the definitions are analogous. Functions with more parameters are a bit more complicated: (x,y)=>x+y would be expressed as λx.λy.x+y. We'll see more about this in section Of Lambdas and functions, in Chapter 3, Starting Out with Functions - A Core Concept, and in section Currying, in Chapter 7, Transforming Functions - Currying and Partial Application.

主站蜘蛛池模板: 重庆市| 巫山县| 龙江县| 甘德县| 丰镇市| 石城县| 荣昌县| 六枝特区| 榆社县| 嘉善县| 彭州市| 达日县| 平山县| 锦州市| 长春市| 石景山区| 长垣县| 黎川县| 池州市| 三门县| 顺义区| 洛隆县| 枣庄市| 新乐市| 左贡县| 科尔| 长顺县| 邵东县| 苏州市| 忻州市| 永川市| 定远县| 栾城县| 北流市| 乌拉特后旗| 濮阳市| 华亭县| 凤台县| 彰化县| 临湘市| 休宁县|