箭头函数是什么_它和普通函数有何不同【教程】

箭头函数与普通函数行为完全不同:无this、无arguments、不可new调用;其this在定义时绑定外层,非调用时决定;不绑定arguments需用rest参数;无prototype故不可构造实例。

箭头函数不是普通函数的“简写版”,而是行为完全不同的函数类型——它没有自己的 this、没有 arguments、不能用 new 调用,也不能当对象方法直接使用。

为什么 obj.method() 里用箭头函数会丢掉 this

普通函数的 this 在调用时才决定(比如 obj.fn()this 指向 obj),而箭头函数的 this 是在定义时就从外层“抄”过来的,跟怎么调用无关。

  • 错误写法:const obj = { name: 'Alice', greet: () => console.log(this.name) }; → 输出 undefined(因为箭头函数捕获的是全局 this
  • 正确写法:const obj = { name: 'Alice', greet() { console.log(this.name); } };greet: function() { ... }
  • 想在回调里保持 this?别用箭头函数硬套,改用 .bind(this)function 表达式,或把逻辑提前提取到变量里

arguments 报错 ReferenceError: arguments is not defined 怎么办?

箭头函数压根不绑定 arguments 对象。这不是遗漏,是设计如此。

  • 普通函数能用:function sum() { return Array.from(arguments).reduce((a, b) => a + b); }
  • 箭头函数必须改用 rest 参数:const sum = (...nums) => nums.reduce((a, b) => a + b);
  • 如果封装的是老接口、需要兼容 arguments.callee 或动态参数检查,坚决别用箭头函数

为什么 new MyArrowFunc() 会报 MyArrowFunc is not a constructor

箭头函数没有 prototype,也没有内部的 [[Construct]] 方法,所以根本不能被 new 调用。

  • 查证方式:console.log(() => {}.prototype); → 输出 undefined;而 console.log(function() {}.prototype); → 输出一个对象
  • 构造器场景(如类工厂、插件初始化)必须用普通函数声明或表达式
  • 即使你只写 const Ctor = () => {},后续任何 new Ctor() 都会立即崩溃

真正容易被忽略的点是:箭头函数的 this 继承链一旦形成,就彻底固化了——哪怕外层函数的 this 后续被 call/ap

ply 改变,箭头函数里的 this 也不会跟着变。它抄的是“定义那一刻”的快照,不是实时引用。