当前位置: 代码迷 >> 综合 >> 箭头函数与普通 function 的区别
  详细解决方案

箭头函数与普通 function 的区别

热度:69   发布时间:2024-02-09 01:26:12.0

1、书写上的区别

箭头函数的语法比普通函数更加简洁,而且在一定情况下还可以简写,比如:

function fun(x, y) {return x + y;
}let fun = (x, y) => { return x + y };//1. 如果 () 内只有一个参数,可以省略 ()
//2. 如果 {} 内只有一句 return ...,可以省略 return 和 {}

2、参数上的区别

普通函数的参数是 arguments,而箭头函数是 arg,比如:

let arr = [1,2,3]~function(){console.log(arguments);
}(arr);     //输出 [1,2,3]let a = (...arg) => { console.log(arg); 
}
a(arr);     //输出[1,2,3]

3、this 指向的区别

箭头函数没有自己的 this,它里面的 this 是继承所属上下文中的 this,而且使用 call 与 apply 都无法改变

let obj = { name: 'obj' }function fun1() {console.log(this);
} 
fn1.call(obj); let fun2() => { console.log(this); }
fn2.call(obj); 

4、可否使用 new 关键字

箭头函数不能使用 new 生成构造函数,因为箭头函数没有 prototype,而 construct 在 prototype 里面

function Fun1() { this.x = 100; } 
let f1 = new Fn1; let Fun2 = () => { this.x = 200; }
let f2 = new Fun2; //输出 Fun2 is not a constructor
  相关解决方案