欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

JavaScript ES6 箭头函数与 this 绑定

时间:2026年08月12日 04:50:02 浏览:1

箭头函数语法


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


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

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

// 单个参数可省略括号
const square = x => x * x;

// 返回对象需加括号
const getObj = () => ({ name: 'test' });

this 绑定差异


function Person(name) {
this.name = name;
// 传统函数,this 指向调用者
setTimeout(function() {
console.log(this.name); // undefined(非严格模式为 window)
}, 100);

// 箭头函数,this 继承外层作用域
setTimeout(() => {
console.log(this.name); // 正确输出
}, 100);
}
new Person('张三');

适用场景



  • 回调函数(如事件监听、定时器)

  • 数组方法(map、filter、reduce)

  • 不改变 this 的场合


箭头函数是现代 JavaScript 开发中的首选写法。