likes
comments
collection
share

【JS】箭头函数和普通函数区别

作者站长头像
站长
· 阅读数 28

千里之行,始于足下

箭头函数和普通函数可能表明看起来差不多,但它们有很大的不同的。本文主要介绍一下两者的差异对比,毕竟细节决定决定每一个未来。

主要以下5个方面的区别:

  • 语法
  • this(上下文)
  • 作为方法使用
  • 作为构造函数使用
  • 参数绑定

语法

箭头函数可以省略参数的圆括号,且提供隐式返回写法。

//箭头函数语法
const square = x => x*x 

//普通函数 
function square(x){
    return x*x 
}

箭头函数返回对象时,返回对象字面量要加括号

// error
 const objFn = () => {name: '宝儿姐'};  //undefined

// better 加括号对象字面量
const objFn = () => ({name: '宝儿姐'});  // {name: '宝儿姐'}

// better return写法
const objFn = () => {
    return {
        name: '宝儿姐'
    }
};

this

箭头函数没有单独的this,普通function函数this根据上下文决定this指向。

  • 如果函数是一个构造函数,this指向一个新对象
  • 如果函数是一个对象的方法,this指向这个对象
  • 严格模式下的函数调用,this指向undefined
  • .....
function normalThis(){ 
    console.log(this) // this指向document
} 
document.addEventListener('click', normalThis);
const arrowThis = () => { 
    console.log(this);  // this 输出window对象 ( global object)
} 
document.addEventListener('click', arrowThis) 

箭头函数不能使用call, bind, apply来改变this指向。

function normalThis(){
    console.log(this)
}
normalThis.call(12); // 输出 12 

const arrowThis = () => { 
    console.log(this) 
}
arrowThis.call(12) // 输出 Window ( global object)

作为方法使用

作为方法使用时,由于箭头函数不会创建自己的this,只会从自己的作用域链继承上一层this. 如下例子箭头函数输出this.x为undefined,此时this是window

const obj = {
    x: 12, 
    normalFn: function(){ 
        console.log(this.x, this) 
    }, 
    arrowFn: () => { console.log(this.x, this) } 
};
    obj.normalFn(); // 输出: 12, Object(...) 
    obj.arrowFn(); // 输出: undefined, global object

作为构造函数使用

通常普通函数能够用new关键字用作构造函数,但是箭头函数不允许。

function Normal(v){ 
    this.v = v; 
};
const normal = new Normal(12); // Normal {v: 12} 

// 箭头函数不允许使用new
const Arrow = v => { this.v = v; };
const arrow = new Arrow(12); // typeError: arrow is not a constructor

arguments参数

普通函数有arguments对象,但箭头函数没有

// 普通函数
function sum(){
    return arguments[0] + arguments[1];
}
sum(2,3); //5

// 箭头函数
const sumArrow = () => { return arguments[0] + arguments[1]; }; //报错 没有arguments对象

其他区别

  • 箭头函数没有prototype
const p = () => {}
console.log(p.prototype) // undefined
  • 箭头函数不支持yield,因此箭头函数不能用作函数生成器。
转载自:https://juejin.cn/post/7047442947385589767
评论
请登录