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

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.

主站蜘蛛池模板: 科尔| 榆树市| 肇州县| 且末县| 温泉县| 普陀区| 漠河县| 建阳市| 霍州市| 宁明县| 皮山县| 通江县| 淄博市| 寻甸| 揭西县| 雅江县| 綦江县| 普定县| 德保县| 越西县| 丹巴县| 乳源| 龙南县| 鸡西市| 柳江县| 明水县| 南充市| 郑州市| 镇沅| 久治县| 同江市| 新泰市| 剑阁县| 衡山县| 车险| 金山区| 霍邱县| 濮阳市| 波密县| 乌兰浩特市| 浏阳市|