Understanding Multiple Arrow Functions in JavaScript
In JavaScript, you may encounter code like this:
e.preventDefault(); /// Do something here }
Curried Functions
This code demonstrates a curried function. A curried function is a function that returns a function, allowing you to partially apply arguments.
Consider the following example (without arrow functions):
const add = (x, y) => x + y add(2, 3) //=> 5
In curried form:
const add = x => y => x + y
Without arrow functions:
const add = function (x) { return function (y) { return x + y } }
Focus on the Return Value
Arrow functions behave as follows (paying attention to the return value):
const f = someParam => returnValue
So, in our add function, a number returns a function:
const add = x => (y => x + y)
This means add of a number returns a function:
add(2) // returns (y => 2 + y)
Calling Curried Functions
To use a curried function, call it differently:
add(2)(3) // returns 5
This is because the first function call returns a second function. Only the second function call gives the actual result.
Application to Your Code
In your code:
handleChange = field => e => { e.preventDefault() /// Do something here }
Without arrow functions:
handleChange = function(field) { return function(e) { e.preventDefault() // Do something here // return ... }; };
Since arrow functions bind this lexically, it looks more like this:
handleChange = function(field) { return function(e) { e.preventDefault() // Do something here // return ... }.bind(this) }.bind(this)
This means that handleChange creates a function for a specified field. It's a React technique for setting up event listeners for each input without duplication.
Even More Arrows
More than two arrow functions can be sequenced:
const three = a => b => c => a + b + c const four = a => b => c => d => a + b + c + d three (1) (2) (3) // 6 four (1) (2) (3) (4) // 10
Currying and Arity
Currying can surprise you. Here, $ is defined as a curried function with two parameters, but you can provide any number of arguments:
const $ = x => k => $ (k (x)) const add = x => y => x + y const mult = x => y => x * y $ (1) // 1 (add (2)) // + 2 = 3 (mult (6)) // * 6 = 18 (console.log) // 18 $ (7) // 7 (add (1)) // + 1 = 8 (mult (8)) // * 8 = 64 (mult (2)) // * 2 = 128 (mult (2)) // * 2 = 256 (console.log) // 256
The above is the detailed content of How Do Multiple Nested Arrow Functions Work in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!