You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript:请举例说明Currying(柯里化)在JavaScript中的应用

Currying in JavaScript: Practical Examples & Use Cases

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 multiplyBy5 make 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 10:08:04