JavaScript 函数完全指南:声明、表达式、箭头函数与闭包

小飞兽 JavaScript 388 次阅读 2026-05-07

Introduction

函数是 JavaScript 的一等公民(first-class citizen):函数可以赋值给变量、作为参数传递、作为返回值。理解函数声明(hoisting)、函数表达式、箭头函数、IIFE、构造函数以及 this 的绑定机制,是掌握 JavaScript 编程的核心。

函数声明 vs 函数表达式

/* 函数声明:会被提升,可以在定义前调用 */
greet('小马'); // 'Hello, 小马!'
function greet(name) {
    return 'Hello, ' + name + '!';
}

/* 函数表达式:不会被提升,必须先定义后调用 */
const greet2 = function(name) {
return 'Hello, ' + name + '!';
};

/* 箭头函数(ES6+):不绑定自己的 this */
const greet3 = (name) => 'Hello, ' + name + '!';

// 单参数可省略括号
const double = x => x * 2;

// 多行函数体需要 return
const add = (a, b) => {
const result = a + b;
return result;
};

// 箭头函数没有 arguments 对象
const sum = (...nums) => nums.reduce((a, b) => a + b, 0);
sum(1, 2, 3, 4); // 10

this 绑定机制

/* 1. 普通函数:this 由调用方式决定 */
const obj = {
    name: '小马',
    greet() {
        return 'Hi, I am ' + this.name; // this = obj
    }
};

/* 2. 箭头函数:this 继承外层作用域(词法 this)*/
const obj2 = {
name: '小马',
greet() {
const inner = () => 'Hi, I am ' + this.name; // this = obj2
return inner();
}
};

/* 3. 构造函数的 this */
function Person(name) {
this.name = name;
}
const p = new Person('小马');

/* 4. 手动绑定 this:call / apply / bind */
function show(message) {
return this.name + ': ' + message;
}
show.call({ name: '小腾' }, '你好'); // '小腾: 你好'
show.apply({ name: '小飞' }, ['你好']); // '小飞: 你好'
const bound = show.bind({ name: '大山' }, '加油');
bound(); // '大山: 加油'

高阶函数与函数式编程

/* 函数作为参数 */
const numbers = [1, 2, 3, 4, 5];
numbers.filter(n => n % 2 === 0); // [2, 4]
numbers.map(n => n * n);          // [1, 4, 9, 16, 25]
numbers.reduce((sum, n) => sum + n, 0); // 15

/* 函数作为返回值 */
function multiply(factor) {
return number => number * factor;
}
const double = multiply(2);
double(5); // 10

/* IIFE(立即调用函数表达式)*/
(function() {
const privateVar = 'secret';
console.log('IIFE runs immediately');
})();

常见问题

    • 箭头函数没有自己的 this:不能作为构造函数,不能使用 arguments,适用于回调函数。
  • 默认参数:const f = (x = 10) => x;传 undefined 也会触发默认值。
  • 递归函数:注意递归深度不要超过 JavaScript 引擎调用栈限制。

延伸阅读