前端小知識,面試,長知識必備---箭頭函數與普通函數(function)的異同

前端小知識,面試,長知識必備.3

箭頭函數與普通函數(function)的區別是什麼?

箭頭函數是普通函數的簡寫,可以更優雅的定義一個函數,和普通函數相比,箭頭函數有以下幾點差異:

1、函數體內的 this 對象,就是定義時所在的對象,而不是使用時所在的對象。

2、不可以使用 arguments 對象,該對象在函數體內不存在。如果要用,可以用 rest 參數代替。

3、不可以使用 yield 命令,因此箭頭函數不能用作 Generator 函數。

4、不可以使用 new 命令,因爲:

  • 沒有自己的 this,無法調用 call,apply。
  • 沒有 prototype 屬性 ,而 new 命令在執行時需要將構造函數的 prototype 賦值給新的對象的 __proto__

new 過程大致是這樣的:

function newFunc(father, ...rest) {
  var result = {};
  result.__proto__ = father.prototype;
  var result2 = father.apply(result, rest);
  if (
    (typeof result2 === 'object' || typeof result2 === 'function') &&
    result2 !== null
  ) {
    return result2;
  }
  return result;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章