7. 函數(shù)

2018-02-24 16:11 更新
  • 7.1?使用函數(shù)聲明代替函數(shù)表達(dá)式。

    為什么?因?yàn)楹瘮?shù)聲明是可命名的,所以他們?cè)谡{(diào)用棧中更容易被識(shí)別。此外,函數(shù)聲明會(huì)把整個(gè)函數(shù)提升(hoisted),而函數(shù)表達(dá)式只會(huì)把函數(shù)的引用變量名提升。這條規(guī)則使得箭頭函數(shù)可以取代函數(shù)表達(dá)式。

      // bad
      const foo = function () {
      };
    
      // good
      function foo() {
      }
  • 7.2?函數(shù)表達(dá)式:

    // 立即調(diào)用的函數(shù)表達(dá)式 (IIFE)
    (() => {
      console.log('Welcome to the Internet. Please follow me.');
    })();
  • 7.3?永遠(yuǎn)不要在一個(gè)非函數(shù)代碼塊(if、while?等)中聲明一個(gè)函數(shù),把那個(gè)函數(shù)賦給一個(gè)變量。瀏覽器允許你這么做,但它們的解析表現(xiàn)不一致。

  • 7.4?注意:?ECMA-262 把?block?定義為一組語(yǔ)句。函數(shù)聲明不是語(yǔ)句。閱讀 ECMA-262 關(guān)于這個(gè)問(wèn)題的說(shuō)明。

    // bad
    if (currentUser) {
      function test() {
        console.log('Nope.');
      }
    }
    
    // good
    let test;
    if (currentUser) {
      test = () => {
        console.log('Yup.');
      };
    }
  • 7.5?永遠(yuǎn)不要把參數(shù)命名為?arguments。這將取代原來(lái)函數(shù)作用域內(nèi)的?arguments?對(duì)象。

    // bad
    function nope(name, options, arguments) {
      // ...stuff...
    }
    
    // good
    function yup(name, options, args) {
      // ...stuff...
    }
  • 7.6?不要使用?arguments。可以選擇 rest 語(yǔ)法?...?替代。

    為什么?使用?...?能明確你要傳入的參數(shù)。另外 rest 參數(shù)是一個(gè)真正的數(shù)組,而?arguments是一個(gè)類數(shù)組。

      // bad
      function concatenateAll() {
        const args = Array.prototype.slice.call(arguments);
        return args.join('');
      }
    
      // good
      function concatenateAll(...args) {
        return args.join('');
      }
  • 7.7?直接給函數(shù)的參數(shù)指定默認(rèn)值,不要使用一個(gè)變化的函數(shù)參數(shù)。

    // really bad
    function handleThings(opts) {
      // 不!我們不應(yīng)該改變函數(shù)參數(shù)。
      // 更加糟糕: 如果參數(shù) opts 是 false 的話,它就會(huì)被設(shè)定為一個(gè)對(duì)象。
      // 但這樣的寫法會(huì)造成一些 Bugs。
      //(譯注:例如當(dāng) opts 被賦值為空字符串,opts 仍然會(huì)被下一行代碼設(shè)定為一個(gè)空對(duì)象。)
      opts = opts || {};
      // ...
    }
    
    // still bad
    function handleThings(opts) {
      if (opts === void 0) {
        opts = {};
      }
      // ...
    }
    
    // good
    function handleThings(opts = {}) {
      // ...
    }
  • 7.8?直接給函數(shù)參數(shù)賦值時(shí)需要避免副作用。

    為什么?因?yàn)檫@樣的寫法讓人感到很困惑。

    var b = 1;
    // bad
    function count(a = b++) {
      console.log(a);
    }
    count();  // 1
    count();  // 2
    count(3); // 3
    count();  // 3
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)