JS中箭头函数和普通函数的区别
ES6标准新增了一种新的函数:箭头函数Arrow Function
let fn = () => {};
箭头函数是一种非常好用的语法,其有着简洁的函数声明方法,还有很多的简写方式,下面详细的介绍一些箭头函数与普通函数的区别
箭头函数比普通函数更加简洁
// 箭头函数
let foo = () => {};
// 普通函数
function fn() {};
箭头函数的简写方式
1、省略括号,当箭头函数只有一个参数时,括号可以省略
let foo = item => {
console.log(itme)
}
function fn(num) {
console.log(num)
}
2、省略大括号,当箭头函数的函数体只有一个 return
语句时,可以省略 return
关键字和方法体的大括号
let foo = (num1, num2) => num1 + num2
function fn(num1, num2) {
return num1 + num2
}
3、省略大小括号
let foo = x => y => x + y
function fn(x) {
return function(y) {
return x + y
}
}
箭头函数没有自己的this
箭头函数的this
继承其执行上下文中的this
,且使用call/apply
等方无法改变其this
var obj = {
name: 'obj'
}
function bar1() {
console.log(this);
}
let bar2 = () => {
console.log(this);
}
bar1.call(obj) // obj
bar2.call(obj) // window
document.body.onclick = () => {
// this: window 不是当前 body
}
document.body.onclick = function() {
// this: body
}
箭头函数中没有arguments,可以使用…args
let foo = (...args) => {
// console.log(arguments) // Uncaught ReferenceError: arguments is not defined
console.log(...args)
}
foo(1, 2, 3, 4) // 1 2 3 4
箭头函数不能作为构造函数,被new执行
箭头函数中没有this
不能给实例添加属性,且箭头函数没有prototype
let Foo = () => {
this.x = 200
}
const f = new Foo() // Uncaught TypeError: Fn is not a constructor