课程介绍
课程背景
- 前端的主要编程语言为JavaScript
- JavaScript 做为一种融合了多种编程范式的语言,灵活性非常高
- 前端开发人员需要根据场景在不同编程范式间自如切换
- 进一步需要创造领域特定语言抽象业务问题
课程收益
- 了解不同编程范式的起源和适用场景
- 掌握JavaScript 在不同的编程范式特别是函数式编程范式的使用
- 3.掌握创建领域特定语言的相关工具和模式
1. 编程语言
2. 编程范式
是什么
常见编程方式
自项向下
面向过程问题
- 数据与算法关联弱
- 不利于修改和扩充
- 不利于代码重用
面向对象编程五大原则
| 名称 | 说明 |
|---|---|
| 单一职责原则SRP(Single Responsibility Principle) | 一个类的功能要单一,不能包罗万象 |
| 开放封闭原则OCP(Open - Close Principle) | 一个模块在扩展方面是开放的,在修改方面是封闭的 |
| 里式替换原则LSP(the Liskov Substitution Principle LSP) | 子类应该可以替换父类并出现在父类应该出现的任何地方 |
| 依赖倒置原则DIP(the Dependency Inversion Principle DIP) | 具体依赖抽象,上层依赖下层 |
| 接口分离原则ISP(theInterface Segregation PrincipleISP) | 任何依赖要通过接口而不是具体实现 |
面向对象问题
面向对象编程语言的问题在于,它总是附带着所有它需要的隐含环境。你想要一个香蕉,但得到的却是一个大猩猩拿着香蕉,而且还有整个丛林。
——Joe Armstrong (Erlang创始人)
函数式编程
特点
- 函数是“第一等公民”
- 纯函数 / 无副作用
- 高阶函数 / 闭包
聚合转发
const BlogController = {
index(posts) { return Views.index(posts); },
show(post) { return Views.show(post); },
create(attrs) { return Db.create(attrs); },
update(post,attrs) { return Db.update(post, attrs); },
destroy(post) { return Db.destroy(post); },
};
const BlogController = {
index: Views.index ,
show: Views.show,
create: Db.create,
update: Db.update ,
destroy: Db.destroy,
};
纯函数
const retireAge = 60;
function retirePerson(p) {
if (p.age > retireAge) {
p.status= 'retired';
}
}
function retirePerson(p) {
const retireAge = 60;
if (p.age > retireAge) {
return {
...P,
status: 'retired',
};
}
return p;
}
柯里化
function add(a, b, c) {
return a + b + c
}
// 参数重复:
add(1, 2, 5)
add(1, 2, 4)
add(1, 2, 7)
// 闭包:
function curry(fn) {
const arity = fn.length;
return function $curry(...args) {
if(args.length < arity) {
return $curry.bind(null, ...args)
}
return fn.call(null, ...args);
}
}
// 之前参数存入闭包:
const add_ = curry(add);
const add12 = add_(1, 2);
add12(5);
add12(4);
add12(7);
const add1 = add_(1);
add1(2, 5);
add1(3, 5);
组合
Functor
Monad
Applicative
响应式编程
- 异步/离散的函数式编程
- 数据流
- 操作符
- 过滤
- 合并
- 转化
- 高阶