[Javascript] What is JavaScript Function Currying?
JavaScript is Function What
2023-09-14 09:00:54 时间
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');
相关文章
- JavaScript修改DOM节点时,样式优先级的问题
- JavaScript闭包之“词法作用域”
- JavaScript位运算符
- 《javascript模式》读书笔记:容易踩中的那些坑
- 第一百一十二节,JavaScript浏览器检测
- JavaScript -- 正则表达式
- [Javascript] Intl.Collator().compare
- JavaScript 中的执行上下文和调用栈是什么?
- [Javascript] Object.is() vs ===
- 理解JavaScript中的事件处理
- when is backend date format set in Javascript DateFormat
- 【微搭低代码】JavaScript基础知识-变量定义及初始化
- JavaScript中的几个重要概念
- [转载]Selenium実行中にJavaScriptのコードを実行する
- 【华为OD机试 2023】快递投放问题(C++ Java JavaScript Python)
- JavaScript如何实现计时功能。