概念:
常见编程方式:
- 声明式编程:vue 和react
- 命令式编程:明确的指令
- 函数式编程:强调纯函数,react
- 面向对象编程:Java
- 逻辑编程:Prolog语言
- 过程式编程:c语言
JS 是多范式编程语言,支持多种编程方式
vue是主要声明式编程,在生命周期中可以使用命令式编程
react整体而言是声明式编程,在ref操作dom时(如获取focus())和生命周期中可以使用命令式编程
1. 命令式编程:
关注程序的执行 和 状态的改变;侧重于如何做,比如说要遍历去求和这个过程
let array = [1, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < array.length; i++) {
sum += array[i];
}
console.log(sum);
2. 声明式编程:
侧重于描述 应该做什么,比如 做的是求和这件事
let array = [1, 2, 3, 4, 5];
let sum = array.reduce((acc, curr) => acc + curr, 0);
console.log(sum);
3. 函数式编程 :
将计算视为数学函数的求值;
- 纯函数
- 不可变
- 函数组合
- 高阶函数
const add = (a, b) => a + b;
const multiply = (a, b) => a * b;
const calculate = (x, y) => multiply(add(x, y), 2);
console.log(calculate(2, 3));
4. 面向对象编程
比如java, 数据和操作方法全都封装在对象中
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
let person = new Person('John', 30);
console.log(person.greet());