JavaScript:请举例说明Currying(柯里化)在JavaScript中的应用
Currying is all about breaking a function that takes multiple arguments into a sequence of functions that each take one (or fewer) arguments. Each time you call part of it, you get a new function that waits for the remaining arguments. Let's walk through some real-world examples to make this stick.
Basic Example: Reusable Math Functions
Let's start with a simple multiplication example—this mirrors the arrow function structure you shared:
// Curried multiply function: takes one number, returns a function that takes another const multiply = (num1) => (num2) => num1 * num2; // Create a dedicated function that multiplies any number by 5 const multiplyBy5 = multiply(5); // Use it with different second arguments console.log(multiplyBy5(3)); // Output: 15 console.log(multiplyBy5(7)); // Output: 35
Here, we "pre-set" the first argument (5) once, then reuse multiplyBy5 whenever we need to multiply something by 5. Super handy for repeated operations!
Practical Use Case: API Request Wrappers
Currying shines when you want to create reusable API clients with pre-configured base URLs. Instead of repeating the base URL every time, you can lock it in upfront:
// Curried function to create API callers const createApiCaller = (baseUrl) => (endpoint) => (params) => { // In a real app, this would be a fetch/axios call console.log(`Fetching data from: ${baseUrl}${endpoint}`); console.log(`With parameters:`, params); }; // Create a caller for GitHub's API const githubApi = createApiCaller('https://api.github.com'); // Narrow it down to the users endpoint const githubUsers = githubApi('/users'); // Now make requests without repeating the base URL githubUsers({ username: 'michaelnino' }); // Output: // Fetching data from: https://api.github.com/users // With parameters: { username: 'michaelnino' }
Another Use Case: Event Handlers with Fixed Context
Currying lets you pass fixed values to event handlers without messy bind calls or anonymous functions. For example, attaching a click handler that already knows what message to show:
// Curried click handler that takes a message first, then the event const handleButtonClick = (message) => (event) => { alert(`${message}! You clicked element: ${event.target.id}`); }; // Attach to a button—we pass the message now, and the event gets passed automatically document.getElementById('save-btn').addEventListener('click', handleButtonClick('Saved successfully'));
When the button is clicked, the event object is automatically passed to the inner function, so we don't have to juggle arguments manually.
Why Bother with Currying?
- Reusability: Create specialized functions from general ones without repeating code.
- Readability: Function names like
multiplyBy5make your code's intent crystal clear. - Function Composition: Curried functions play nicely with functional programming patterns like composing multiple small functions together.
内容的提问来源于stack exchange,提问作者Michael Niño

