编程范式(Programming Paradigm)是代码组织的思维模式和风格。JavaScript 的灵活性在于它原生支持多种范式,开发者可以根据需求混合使用。
核心思想:将程序视为一系列相互协作的对象,每个对象包含数据(属性)和操作数据的方法(函数)。
// ES5:构造函数 + 原型链
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function () {
return `Hello, I'm ${this.name}`;
};
const alice = new Person("Alice", 30);
alice.greet(); // "Hello, I'm Alice"
// ES6:class 语法糖(本质仍是原型继承)
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
// 方法重写
super.speak();
console.log(`${this.name} barks!`);
}
}
const dog = new Dog("Rex", "Shepherd");
dog.speak();
OOP 关键概念在 JS 中的体现:
核心思想:将程序视为一系列数学函数的计算,避免状态变化和可变数据。
// 1. 函数是一等公民(可作为参数、返回值)
const multiply = (a, b) => a * b;
const applyOperation = (fn, x, y) => fn(x, y);
applyOperation(multiply, 3, 4); // 12
// 2. 高阶函数(接受/返回函数)
const createMultiplier = factor => num => num * factor;
const double = createMultiplier(2);
double(5); // 10
// 3. 纯函数:相同输入 => 相同输出,无副作用
const pureAdd = (a, b) => a + b; // 纯函数
let total = 0;
const impureAdd = x => {
total += x;
return total;
}; // 不纯
// 4. 不可变数据(结合展开运算符、数组方法)
const original = [1, 2, 3];
const newArray = [...original, 4]; // 不修改原数组
const doubled = original.map(x => x * 2); // [2,4,6]
// 5. 函数组合
const add = x => x + 2;
const square = x => x * x;
const compose = (f, g) => x => f(g(x));
const addThenSquare = compose(square, add);
addThenSquare(3); // (3+2)^2 = 25