复习JavaScript基础--箭头函数与普通函数有什么区别

117 阅读1分钟

面试深受打击了,时候回炉重造了!!!! 怀挺

1. 箭头函数与普通函数有什么区别???

    1. this的指向不同
let a = ()=>{}
console.log(a.prototype) // undefined


let a = function(){}
console.log(a.prototype) // {constructor: ƒ}

~ 结论:箭头函数没有prototype(原型),所以箭头函数本身没有this

2.如果箭头函数外层没有普通函数,不管是否是严格模式还是非严格模式,this指向都是window; 如果普通函数那就会this指向是undefined

let foo = function(){
    console.log(this)
}
foo()  // window


let foo = ()=>{console.log(this)};
foo(); // window



'use strict'
let foo = ()=>{console.log(this)};
foo(); // window


'use strict'
let foo = function() {console.log(this)};
foo(); // undefined

~ 总结: 箭头函数与普通函数,如果箭头函数外层没有普通函数,他们两个都是指向window如果是严格模式下的话:箭头函数是指向window,普通函数指向是undefined

3.箭头函数不支持new.target

let aa = function(){
    console.log(new.target)
}
aa() // undefined

let a = ()=>{
    console.log(new.target)
}
a(); // VM943:2 Uncaught SyntaxError: 

4.箭头函数不支持重命名函数参数,普通函数的函数参数支持重命名

function fun1(a, a){
    console.log(a, arguments)
}
fun1(1,2) // 2 Arguments(2) [1, 2, callee: ƒ, Symbol(Symbol.iterator): ƒ]

let fun2 = (a, a) => {
    console.log(a); 
} 
fun2(1,1) // Duplicate parameter name not allowed in this context

5.箭头函数相对于普通函数语法更简洁优雅