箭頭函數(shù)和普通函數(shù)的主要區(qū)別是什么?

箭頭函數(shù)和普通函數(shù)的主要區(qū)別:

  • this的指向問題,箭頭函數(shù)是不存在this的(也是箭頭函數(shù)和普通函數(shù)最主要的區(qū)別)
  • 箭頭函數(shù)沒有原型prototype
  • 箭頭函數(shù)沒有argements(類數(shù)組)

一、this的指向問題(也是箭頭函數(shù)和普通函數(shù)最主要的區(qū)別)

(1)箭頭函數(shù)是不存在this的,它的this是繼承自父執(zhí)行的上下文中,而且不能使用call、apply、bind來改變this的指向,箭頭函數(shù)中的this是永遠(yuǎn)不會改變的。

比如這里的箭頭函數(shù)的this.x,箭頭函數(shù)和say平級以key:value的形式,也就是箭頭函數(shù)本身所在的對象為obj,而obj的父執(zhí)行上下文就是window,所以這里的this.x實(shí)際上表示的是window.x,因此輸出11.

var x = 11;
var obj = {
  x:22,
  say:()=>{
    console.log(this.x);
  }
}
obj.say();//11

(2) 普通函數(shù)this指向的是它的直接調(diào)用者。

// 普通函數(shù)
var name = "ice";
var obj = {
  name: "leaf",
  getName: function() {
    console.log(this.name);//this指的是它的直角調(diào)用者,就是obj,所以返回leaf
  }
};
obj.getName(); // 此時(shí)指向調(diào)用者obj,輸出leaf

//箭頭函數(shù)
var name = "ice";
var obj = {
  name: "leaf",
  getName: () => {
    console.log(this.name); 
    // 指向定義時(shí)所在的對象,name是在全局的環(huán)境下創(chuàng)建的,所有this指向的是全局對象
}
};

obj.getName();//ice

var obj1 = { name: "haha" };
obj.getName.call(obj1); // 無法改變this指向  輸出還是ice

二、箭頭函數(shù)沒有原型prototype,是不能夠被作為構(gòu)造函數(shù)調(diào)用的,會報(bào)錯(cuò);

//普通函數(shù)
function Person() {
  console.log("person");
}//定義一個(gè)構(gòu)造函數(shù)

const myFather = new Person();//構(gòu)造函數(shù)的實(shí)例化對象

//箭頭函數(shù)
let Person2 = () => {
  console.log("person2");
}
console.log(Person2.prototype);//undefined
const myFather2 = new Person2();////Person2 is not a constructor

三、箭頭函數(shù)沒有argements(類數(shù)組),只能基于...arg來獲取參數(shù)集合(數(shù)組)

let Person2 = () => {
  console.log(person2.argements);
}
Person2(10,20,30)// Person3 is not defined

//只能使用...arg來獲取參數(shù)集合(數(shù)組)
let Person2 = (...arg) => {
  console.log(arg);
}
Person2(10, 20, 30)// [10, 20, 30]

持續(xù)補(bǔ)充更新,記錄不好的地方望指出修改,共同進(jìn)步~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容