[Javascript] What is JavaScript Function Currying?
2015-11-29 00:50
531 查看
Currying is a core concept of functional programming and a useful tool for any developer's toolbelt.
Example 1:
Example 2:
Example 3:
Example 4: include ramda library:
Example 5: multi placeholders:
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权威指南学习笔记(二)
- javascript实例
- html/jsp 引用百度地图极其部分功能
- 整理Javascript基础入门学习笔记
- JavaScript学习小结(7)之JS RegExp
- javascript实现C语言经典程序题
- js性能优化技巧
- 通用javascript代码判断版本号是否在版本范围之间
- javascript实现网页中涉及的简易运动(改变宽高、透明度、位置)
- javascript实现拖动元素交换位置
- javascript高级编程之函数表达式 递归和闭包函数
- Javascript闭包实例详解
- 整理Javascript基础语法学习笔记
- 基于javascript代码实现通过点击图片显示原图片
- javascript省市区三级联动下拉框菜单实例演示
- JavaScript页面加载执行多个函数
- javascript权威指南学习笔记(一)
- js操作表格的属性
- Visual Studio Code For Mac 支持 ejs 模版视窗编辑识别为html
- 【JavaScript】js操作本地文件