全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-16 7 分钟 ✍️ juanwangdev

箭头函数

箭头函数提供了更简洁的函数语法,且不绑定自己的 this

基本语法

标准形式

JavaScript
// 传统函数
const add = function(a, b) {
  return a + b;
};

// 箭头函数
const add = (a, b) => {
  return a + b;
};

简写形式

单参数省略括号:

JavaScript
const double = n => n * 2;

单表达式省略return:

JavaScript
const add = (a, b) => a + b;

无参数:

JavaScript
const sayHi = () => console.log('Hi');

返回对象需加括号:

JavaScript
const createUser = name => ({ name, age: 18 });

this绑定

箭头函数没有自己的 this,继承外层作用域的 this

JavaScript
const obj = {
  name: 'Tom',
  // 传统函数:this指向调用者
  greetTraditional: function() {
    console.log(this.name);  // Tom
  },
  // 箭头函数:this继承外层
  greetArrow: () => {
    console.log(this.name);  // undefined(外层this是window/undefined)
  }
};

解决回调中的this问题

JavaScript
function Timer() {
  this.seconds = 0;

  // 传统写法
  setInterval(function() {
    this.seconds++;  // this指向window,报错
  }, 1000);

  // 箭头函数
  setInterval(() => {
    this.seconds++;  // this正确指向Timer实例
  }, 1000);
}

不适用场景

对象方法

JavaScript
const obj = {
  name: 'Tom',
  greet: () => console.log(this.name)  // 错误:this不是obj
};

// 正确写法
const obj = {
  name: 'Tom',
  greet() { console.log(this.name); }  // 方法简写
};

构造函数

JavaScript
const Person = (name) => {
  this.name = name;  // 错误:没有this
};

const p = new Person('Tom');  // TypeError

事件处理器

JavaScript
button.addEventListener('click', () => {
  console.log(this);  // this不是button
});

// 正确写法
button.addEventListener('click', function() {
  console.log(this);  // this是button
});

原型方法

JavaScript
function Person(name) {
  this.name = name;
}

Person.prototype.greet = () => {
  console.log(this.name);  // 错误:this不是实例
};

// 正确写法
Person.prototype.greet = function() {
  console.log(this.name);
};

其他特性

没有arguments

JavaScript
const fn = () => {
  console.log(arguments);  // ReferenceError
};

// 使用剩余参数替代
const fn = (...args) => {
  console.log(args);
};

没有prototype

JavaScript
const fn = () => {};
console.log(fn.prototype);  // undefined

不能作为Generator

JavaScript
const fn = *() => {};  // SyntaxError

箭头函数vs传统函数

特性箭头函数传统函数
this词法绑定动态绑定
arguments
prototype
构造函数不能可以
yield不能可以
语法简洁冗长

要点总结

  1. 箭头函数语法简洁,单表达式可省略 return
  2. 返回对象需用括号 ({})
  3. 没有自己的 this,继承外层作用域
  4. 不适用:对象方法、构造函数、事件处理器
  5. 没有 arguments,用剩余参数替代

📝 发现内容有误?点击此处直接编辑

← 上一篇 参数传递
下一篇 → 返回值
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库