✅ 1. 递归(Recursion)
函数调用自身,适合处理树状结构、分治问题。
function factorial(n) {
if (n === 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // 输出 120
✅ 2. 闭包(Closure)
内部函数“记住”了外部函数的变量,即使外部函数已经执行完。
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
✅ 3. 原型链(Prototype Chain)
对象找不到属性时会向其 __proto__ (即构造函数的 prototype)查找。
function Person() {}
Person.prototype.sayHi = function() {
console.log("Hi!");
};
const p = new Person();
p.sayHi(); // Hi!
✅ 4. 异步编程(Async / Promise / Callback)
JS 是单线程,用回调、Promise、async/await 处理异步任务。
async function getData() {
const res = await fetch("https://api.example.com");
const data = await res.json();
console.log(data);
}
getData();
✅ 5. 作用域(Scope)
变量访问是基于作用域链决定的,有函数作用域、块级作用域。
function outer() {
let a = 1;
function inner() {
console.log(a); // 能访问到 a
}
inner();
}
outer();
✅ 6. this 指向
this 取决于函数被调用的方式,箭头函数不绑定自己的 this。
const obj = {
name: "Logan",
sayHi() {
console.log(this.name);
}
};
obj.sayHi(); // Logan
✅ 7. 事件循环 & 执行栈
JS 按顺序执行同步代码,异步任务放入队列中排队执行。
console.log(1);
setTimeout(() => console.log(2), 0);
console.log(3);
// 输出顺序:1 3 2
✅ 8. 数据类型与引用类型
基础类型(number、string等)是值传递,引用类型(对象、数组)是地址传递。
let a = {x: 1};
let b = a;
b.x = 2;
console.log(a.x); // 2
✅ 9. 高阶函数(Higher-order Function)
函数可以接收函数作为参数或返回另一个函数。
function add(x) {
return function(y) {
return x + y;
};
}
console.log(add(5)(3)); // 8
✅ 10. 模块化(ES Module)
JS 使用模块化管理代码,export 导出,import 引入。
// utils.js
export function sum(a, b) {
return a + b;
}
// main.js
import { sum } from './utils.js';
console.log(sum(2, 3)); // 5