JavaScript 中的高级函数是掌握编程精髓的关键,它们让代码更简洁且功能更强大。以下是核心概念及示例:

1. 闭包(Closure) 🧠

闭包是指函数可以访问并记住其词法作用域,即使该函数在其作用域外执行。

function outer() {
  let count = 0;
  return () => {
    count++;
    console.log(count);
  };
}
const increment = outer();
increment(); // 1
increment(); // 2
Closure

2. 高阶函数(Higher-Order Functions) 📈

高阶函数是接受函数作为参数或返回函数的函数,例如 mapfilter 等数组方法。

const numbers = [1, 2, 3];
numbers.map(x => x * 2); // [2, 4, 6]
Higher_order_functions

3. 箭头函数(Arrow Function) 🔄

箭头函数提供更简洁的语法,且绑定 this 关键字的规则与传统函数不同。

const greet = (name) => `Hello, ${name}!`;
greet("World"); // "Hello, World!"
Arrow_function

4. 原型与原型链(Prototype & Prototype Chain) 🧩

每个对象都有一个原型,通过原型链实现继承。

function Person(name) {
  this.name = name;
}
Person.prototype.greet = function() {
  console.log(`Hi, my name is ${this.name}`);
};
const p = new Person("Alice");
p.greet(); // Hi, my name is Alice
Prototype_chain

如需深入了解,可访问 JavaScript 高级函数实战教程 获取更多示例与进阶技巧。