Javascript函数如何定义_箭头函数和普通函数有何不同?

JavaScript中函数分为普通函数和箭头函数:前者支持this动态绑定、arguments、new调用及Generator;后者继承外层this、无arguments和new.target、不可构造、不支持Generator。

JavaScript 中定义函数主要有两种方式:普通函数(function 声明或表达式)和箭头函数(=>)。它们在语法、this 绑定、arguments 对象、new 调用支持等方面有本质区别,选错可能引发隐蔽 bug。

语法写法不同

普通函数可使用函数声明或函数表达式:

function sayHello(name) { return `Hello, ${name}`; }
const sayHello = function(name) { return `Hello, ${name}`; };

箭头函数必须是表达式,且语法更紧凑:

const sayHello = (name) => `Hello, ${name}`;
const add = (a, b) => a + b;
const log = () => console.log('no params');

单参数时可省括号,单表达式语句可省花括号和 return。

this 指向完全不同

普通函数的 this 在调用时动态确定,取决于调用方式(如 obj.method() 中 this 是 obj,独立调用则为 undefined 或全局对象)。

箭头函数没有自己的 this,它会沿作用域链向上查找外层普通函数的 this,始终继承定义时所在上下文的 this。

这意味着:

  • 箭头函数不能用作对象方法(除非外层 this 正确绑定)
  • 无法通过 call/apply/bind 改变其 this
  • 适合用在回调中避免 this 丢失,比如事件监听或定时器

没有 arguments 和 new.target

普通函数内部可访问 arguments 类数组对象,获取所有实参;也可用 new.target 判断是否被 new 调用。

箭头函数没有 arguments,也没有 new.target。需要类数组参数时得用剩余参数(...args)代替。

例如:

const sum = (...nums) => nums.reduce((a, b) => a + b, 0);

同时,箭头函数不能作为构造函数——调用 new 会直接报错。

不能用作 Generator 函数

普通函数可用 function* 定义 Generator,支持 yield;箭头函数不支持 * 语法,也不能 yield。

如果需要迭代逻辑或异步流程控制,必须用普通函数。