箭头函数与普通函数区别

117 阅读2分钟
1. 箭头函数写法上更加简单,省略了function关键词
  • 返回单条语句下可以省略 return
const fn = (val)=> {    
    return val
}
const arrowFunc = (val) => val
// 普通函数
function normalFunc(val){
    return val
}
2.arguments 对象
  • 箭头函数没有自己的arguments对象
  • 普通函数有自己的arguments对象,并能访问传递给函数的所有参数
function normalFunc() {
    console.log(arguments); // [1, 2, 3]
}
const arrowFunc = () => {
    console.log(arguments); // 报错:arguments is not defined
};

normalFunc(1, 2, 3);
arrowFunc(1, 2, 3);
3.this绑定
  • 箭头函数
    • 没有自己的this,会继承外层作用域的this
    • 适用于上下文一致的场景中
  • 普通函数
    • 有自己的this,取决于调用的对象,谁调用,指向谁
    • 如果是用作方法,则指向该对象
    • 可以通过bind、call、apply改变this的指向
const obj = {
    name: "测试",
    arrowFunc: () => {
        console.log(this.name); // this指向window
        setTimeout(() => {
            console.log(this.name); // this指向window
        }, 100);
    },
    normalFunc: function() {
        console.log(this.name); // 输出:测试
        setTimeout(function() {
            console.log(this.name); // this指向window
        }, 100);
    }
};

obj.arrowFunc();
obj.normalFunc();

var id = 'China'
function normalFunc() {
    console.log(this.id)  // 输出:Shandong        
}
const arrowFunc = () => {
    console.log(this.id)  // 输出:China        
}
normalFunc.call({ id: 'Shandong' });
arrowFunc.call({ id: 'Shandong' });

4.构造函数
  • 箭头函数不是构造函数,不能使用new关键词
    • 没有this
    • 没有prototype属性
    • new执行了什么?
      1.创建了一个新对象 2.将构造函数的prototype指向新对象的__proto__
      3.将this指向这个新对象
      4.执行构造函数
      5.返回这个新对象
  • 普通函数可以作为构造函数使用
const ArrowFunc = () => {};
function NormalFunc() {}

new NormalFunc(); // 正常工作
new ArrowFunc(); // 报错:ArrowFunc is not a constructor

5.prototype属性
  • 箭头函数
    • 没有自己的prototype属性,不能继承
  • 普通函数
    • 有自己的prototype,可以继承
const arrowFunc = () => { };
function normalFunc() { }

console.log(arrowFunc.prototype) // undefined
console.log(normalFunc.prototype) // {}
6.函数提升
  • 箭头函数
    • 先定义,后使用,不能提升
  • 普通函数
    • 可以被提升,允许先使用,然后再定义
console.log(normalFunc()); // 正常调用
console.log(arrowFunc()); // 报错: Cannot access 'arrowFunc' before initialization

function normalFunc() {
    return "normal";
}

const arrowFunc = () => "arrow";

7.箭头函数不是Generator函数,不能使用yield关键词