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}`; };
箭头函数必须是表达式,且语法更紧凑:
立即学习“Java免费学习笔记(深入)”;
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。
标签: javascript java app 区别 作用域 red
还木有评论哦,快来抢沙发吧~