首頁 web前端 前端問答 實例程式碼之ES6箭頭函數實踐

實例程式碼之ES6箭頭函數實踐

Aug 08, 2022 am 10:26 AM
es6

本篇文章為大家帶來了關於javascript的相關知識,其中主要介紹了箭頭函數應用的相關問題,箭頭函數表達式更適用於那些本來需要匿名函數的地方,並且它不能用作構造函數,下面一起來看一下,希望對大家有幫助。

實例程式碼之ES6箭頭函數實踐

【相關推薦:javascript影片教學web前端

##簡介

箭頭函數表達式的語法比函數表達式更簡潔,也沒有自己的this,arguments,super或new.target。箭頭函數表達式更適用於那些本來需要匿名函數的地方,並且它不能用作構造函數。 ---- MDN

基礎用法

參數表示

(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
//相当于:(param1, param2, …, paramN) =>{ return expression; }

// 当只有一个参数时,圆括号是可选的:
(singleParam) => { statements }
singleParam => { statements }

// 没有参数的函数应该写成一对圆括号。
() => { statements }
登入後複製

傳回值表示

let add1 = (num1, num2) => {
  num1 + num2
};
let add2 = (num1, num2) => {
  return num1 + num2
};
let add3 = (num1, num2) => (num1 + num2);
let add4 = (num1, num2) => num1 + num2;

console.log(add1(2, 3));  // undefined
console.log(add2(2, 3)); // 5
console.log(add3(2, 3)); // 5
console.log(add4(2, 3)); // 5
登入後複製

進階

//加括号的函数体返回对象字面量表达式:
let func = () => ({foo: 'bar'})
console.log(func()); // {foo: 'bar'}


//支持剩余参数和默认参数
(param1, param2, ...rest) => { statements }
(param1 = defaultValue1, param2, …, paramN = defaultValueN) => {
statements }

//同样支持参数列表解构
let f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
f();  // 6
登入後複製

this

實例程式碼之ES6箭頭函數實踐

最佳實踐
  • 如果必須使用匿名函數,或者inline 回呼函數,使用箭頭函數。 eslint: prefer-arrow-callback, arrow-spacing


why?語法更簡潔,並且this更符合預期

如果函數邏輯相當複雜,應使用命名函數
    // bad[1, 2, 3].map(function (x) {
      const y = x + 1;
      return x * y;});// good[1, 2, 3].map((x) => {
      const y = x + 1;
      return x * y;});
    登入後複製

  • 如果函數體只有一條語句,且該語句不會產生副作用。使用簡寫方式,隱含回傳;或使用完整寫法,顯式return。
  • eslint: arrow-parens, arrow-body-style
      // bad
      [1, 2, 3].map(number => {
        const nextNumber = number + 1;
        `A string containing the ${nextNumber}.`;
      });
      
      // good
      [1, 2, 3].map(number => `A string containing the ${number}.`);
      
      // good
      [1, 2, 3].map((number) => {
        const nextNumber = number + 1;
        return `A string containing the ${nextNumber}.`;
      });
      
      // good
      [1, 2, 3].map((number, index) => ({
        [index]: number,
      }));
      
      // No implicit return with side effects
      function foo(callback) {
        const val = callback();
        if (val === true) {
          // Do something if callback returns true
        }
      }
      
      let bool = false;
      
      // bad
      foo(() => bool = true);
      
      // good
      foo(() => {
        bool = true;
      });
      登入後複製
    • 當表達式佔多行時,使用括號括起來增強可讀性

      #why?函數開頭和結束更明確
        // bad['get', 'post', 'put'].map(httpMethod => Object.prototype.hasOwnProperty.call(
            httpMagicObjectWithAVeryLongName,
            httpMethod,
          ));// good['get', 'post', 'put'].map(httpMethod => (
          Object.prototype.hasOwnProperty.call(
            httpMagicObjectWithAVeryLongName,
            httpMethod,
          )));
        登入後複製
      • 如果函數只有一個參數,省略括號,省略花括號。否則,一直使用完整寫法,保持一致性。 eslint: arrow-parens
          // bad[1, 2, 3].map((x) => x * x);// good[1, 2, 3].map(x => x * x);// good[1, 2, 3].map(number => (
            `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!`));// bad[1, 2, 3].map(x => {
            const y = x + 1;
            return x * y;});// good[1, 2, 3].map((x) => {
            const y = x + 1;
            return x * y;});
          登入後複製
        • 使用無歧義的=>語法,與=區分開。 eslint: no-confusing-arrow

          // badconst itemHeight = item => item.height > 256 ? item.largeSize : item.smallSize;// badconst itemHeight = (item) => item.height > 256 ? item.largeSize : item.smallSize;// goodconst itemHeight = item => (item.height > 256 ? item.largeSize : item.smallSize);// goodconst itemHeight = (item) => {
            const { height, largeSize, smallSize } = item;
            return height > 256 ? largeSize : smallSize;
          登入後複製

          簡單結論
          • #箭頭函數不能用new來建立建構函式的實例,普通函數可以(因為箭頭函數創建的時候程式不會為它創建construct方法,也就是沒有構造能力,用完就丟掉了,不像普通函數重複利用,因此也不需要構造函數原型,也就是不會自動生成prototype屬性)
          • 程式不會給箭頭函數建立arguments物件
          • #普通函數中的this是動態的,而箭頭函數中的this指向的是緊緊包裹箭頭函數的那個物件(定義時決定的)
          • 箭頭函數不能透過bind、call、apply來改變this的值,但依然可以呼叫這幾個方法(只是this的值不受這幾個方法控制)

          【相關推薦:javascript影片教學web前端

          】####

          以上是實例程式碼之ES6箭頭函數實踐的詳細內容。更多資訊請關注PHP中文網其他相關文章!

        • 本網站聲明
          本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

          熱AI工具

          Undresser.AI Undress

          Undresser.AI Undress

          人工智慧驅動的應用程序,用於創建逼真的裸體照片

          AI Clothes Remover

          AI Clothes Remover

          用於從照片中去除衣服的線上人工智慧工具。

          Undress AI Tool

          Undress AI Tool

          免費脫衣圖片

          Clothoff.io

          Clothoff.io

          AI脫衣器

          AI Hentai Generator

          AI Hentai Generator

          免費產生 AI 無盡。

          熱門文章

          R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
          2 週前 By 尊渡假赌尊渡假赌尊渡假赌
          倉庫:如何復興隊友
          4 週前 By 尊渡假赌尊渡假赌尊渡假赌
          Hello Kitty Island冒險:如何獲得巨型種子
          3 週前 By 尊渡假赌尊渡假赌尊渡假赌

          熱工具

          記事本++7.3.1

          記事本++7.3.1

          好用且免費的程式碼編輯器

          SublimeText3漢化版

          SublimeText3漢化版

          中文版,非常好用

          禪工作室 13.0.1

          禪工作室 13.0.1

          強大的PHP整合開發環境

          Dreamweaver CS6

          Dreamweaver CS6

          視覺化網頁開發工具

          SublimeText3 Mac版

          SublimeText3 Mac版

          神級程式碼編輯軟體(SublimeText3)

          async是es6還是es7的 async是es6還是es7的 Jan 29, 2023 pm 05:36 PM

          async是es6還是es7的

          ES6怎麼求數組反轉 ES6怎麼求數組反轉 Oct 26, 2022 pm 06:19 PM

          ES6怎麼求數組反轉

          es6怎麼找出2個數組中不同項 es6怎麼找出2個數組中不同項 Nov 01, 2022 pm 06:07 PM

          es6怎麼找出2個數組中不同項

          小程式為什麼要將es6轉es5 小程式為什麼要將es6轉es5 Nov 21, 2022 pm 06:15 PM

          小程式為什麼要將es6轉es5

          require是es6語法嗎 require是es6語法嗎 Oct 21, 2022 pm 04:09 PM

          require是es6語法嗎

          es6暫時性死區是什麼意思 es6暫時性死區是什麼意思 Jan 03, 2023 pm 03:56 PM

          es6暫時性死區是什麼意思

          es6 map有序嗎 es6 map有序嗎 Nov 03, 2022 pm 07:05 PM

          es6 map有序嗎

          es2015就是es6嗎 es2015就是es6嗎 Oct 25, 2022 pm 06:51 PM

          es2015就是es6嗎

          See all articles