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

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.

主站蜘蛛池模板: 衢州市| 教育| 弋阳县| 金溪县| 柳林县| 定州市| 舟曲县| 万源市| 广德县| 麟游县| 桐庐县| 彝良县| 九江县| 察隅县| 集安市| 云龙县| 老河口市| 勐海县| 五家渠市| 龙山县| 二手房| 清新县| 离岛区| 敦化市| 怀化市| 华池县| 玉环县| 乐亭县| 天柱县| 镇坪县| 丹棱县| 景洪市| 垦利县| 台江县| 平南县| 平遥县| 吴堡县| 高唐县| 舞钢市| 武安市| 茌平县|