[Javascript] What is JavaScript Function Currying?

Currying is a core concept of functional programming and a useful tool for any developer's toolbelt. 

 

Example 1:

let f = a => b => c => a+b+c;

let result = f(1)(2)(3);
console.log(result); // 6

 

Example 2:

复制代码
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.18.0/ramda.min.js"></script>
</head>
<body>
<div id="one" style="width: 100px;height: 100px;border: 2px solid black">One</div>
<div id="two" style="width: 100px;height: 100px;border: 2px solid black">Two</div>
<div id="three" style="width: 100px;height: 100px;border: 2px solid black">Three</div>
</body>
</html>
复制代码
复制代码
let one = document.getElementById('one');
let tow = document.getElementById('two');
let three = document.getElementById('three');

let f = a => b => c => a.addEventListener(b, (event)=>{
  event.target.style.background = c;
});

f(one)('click')('red');
复制代码

 

Example 3: 

复制代码
let one = document.getElementById('one');
let tow = document.getElementById('two');
let three = document.getElementById('three');

let f = a => b => c => a.addEventListener(b, (event)=>{
  event.target.style.background = c;
});

let oneClickEvent = f(one);
let twoClickEvent = f(two);


oneClickEvent('mouseover')('red');
twoClickEvent('mouseout')('blue');
复制代码

 

Example 4: include ramda library:

复制代码
let one = document.getElementById('one');
let tow = document.getElementById('two');
let three = document.getElementById('three');

let f = R.curry((a,b,c) =>{
  a.addEventListener(b, (event)=>{
    event.target.style.background = c;
  });
});

// with placeholder from Ramda
const clickGreen = f(R.__, 'click', 'green');
clickGreen(one);
复制代码

 

Example 5: multi placeholders:

复制代码
let one = document.getElementById('one');
let tow = document.getElementById('two');
let three = document.getElementById('three');

let f = R.curry((a,b,c) =>{
  a.addEventListener(b, (event)=>{
    event.target.style.background = c;
  });
});

// with placeholder from Ramda
const clickColor = f(R.__, 'click', R.__);
clickColor(one, 'yellow');
clickColor(two, 'grey');
clickColor(three, 'pink');
复制代码

posted @   Zhentiw  阅读(198)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2014-11-29 [AngularJS] Accessing Scope from The Console
2014-11-29 [AngularJS] Accessing Data in HTML -- controllerAs, using promises
2014-11-29 [AngularJS] Directive Definition Objects (DDO)
2014-11-29 [AngularJS] Using the Angular scope $destroy event and method
点击右上角即可分享
微信分享提示