javascript箭头函数怎么用_它与普通函数有何本质区别?

箭头函数是ES6引入的词法绑定this的简洁函数,无自己的this/arguments/super/new.target,不可作构造函数,不支持call/apply/bind修改this,适合回调场景。

箭头函数是 ES6 引入的简洁函数写法,语法更短、没有自己的 thisargumentssupernew.target,也不可作为构造函数使用。它不是普通函数的“简写替代”,而是一种语义不同的函数类型。

怎么用:基本写法和常见形式

箭头函数用 => 定义,省略 function 关键字和 return(单表达式时):

  • 无参数:const fn = () => console.log('hi')
  • 一个参数(括号可省):const square = x => x * x
  • 多个参数必须加括号:const sum = (a, b) => a + b
  • 函数体多行或需显式返回对象字面量时,要用 {}returnconst getUser = () => ({ name: 'Alice', age: 30 })

this 绑定:最核心的区别

普通函数的 this 在调用时动态绑定(取决于如何被调用),而箭头函数没有自己的 this,它会沿作用域链向上查找外层普通函数的 this 值(词法绑定)。

典型场景:对象方法中用定时器或事件回调时,普通函数容易丢失 this,箭头函数天然避免这个问题:

const obj = {
  name: 'Bob',
  regular() {
    setTimeout(function() {
      console.log(this.name); // undefined(this 指向全局或 undefined)
    }, 100);
  },
  arrow() {
    setTimeout(() => {
      console.log(this.name); // 'Bob'(继承外层 arrow 函数的 this)
    }, 100);
  }
};

不能作为构造函数,也没有 arguments

头函数不能用 new 调用,否则报错 TypeError: xxx is not a constructor;它也没有 arguments 对象(可用剩余参数 ...args 替代):

  • const bad = () => { console.log(arguments); }; bad(1,2); // ReferenceError
  • const good = (...args) => { console.log(args); }; good(1,2); // [1, 2]

没有 prototype,不能用 call/apply/bind 改变 this

箭头函数的 this 是静态确定的,无法通过 callapplybind 强制修改。它也没有 prototype 属性,因此不能用于原型继承或 instanceof 判断。

例如:

const fn = () => {};
console.log(fn.prototype); // undefined
console.log(fn.bind({x:1})()); // this 仍是定义时的值,bind 无效

不复杂但容易忽略。用对场景能减少 this 错误,滥用则可能让逻辑难以追踪。关键记住:箭头函数适合需要词法 this 的回调,不适合定义方法或构造器。