天天看點

JavaScript全解析——ES6定義變量與箭頭函數

作者:陸榮濤

ES6定義變量

●我們現在知道定義(聲明)一個變量用的是var

●在ES6中又增加了兩種定義(聲明)變量的方式:let和const

let聲明變量

●用let聲明的變量也叫變量

const聲明變量

●用const聲明的變零叫産量

let和const的差別

●聲明時指派

○用let聲明變量的時候可以不指派

○用const聲明變量的時候 必須 指派

●值的修改

○用let聲明的變量的是可以任意修改的

○用const聲明的變量的是不能修改的,也就是說一經聲明就不允許修改

○但是 用const聲明的對象,對象裡面的屬性的值是可以修改的

<script>
     //注意:這裡的代碼不能整體運作。需要單獨運作。這裡是為了整體做比較
     //  let 和 const 的差別
     
     // 1. 聲明時指派
     let n
     console.log(n) //undefined
     n = 200
     console.log(n) //200
     // 不能定義常量不指派 會報錯
     const n2
     
     // 2. 值的修改
     let n = 100
     console.log(n) //100
     n = 'hello world'
     console.log(n) //hello world
     const str = '我是定義時候就寫好的内容'
     console.log(str)
     // 當你試圖修改一個 const 定義的常量 直接報錯
     str = 'hello world'
 </script>


複制代碼           

let/const和var的差別

●預解析

○var 會進行預解析, 可以先使用後定義

○let/const 不會進行預解析, 必須先定義後使用

●變量重名

○var 定義的變量可以重名, 隻是第二個沒有意義

○let/const 不允許在同一個作用域下, 定義重名變量

●塊級作用域

○var 沒有塊級作用域

○let/const 有塊級作用域

○塊級作用域: 任何一個可以書寫代碼段的 {} 都會限制變量的使用範圍

■if() {}

■for () {}

<script>
    // 注意:代碼不能整體運作需要分開運作,為了對比需要
    //let/const 和 var 的差別
    
    // 1. 預解析
    console.log(n) //undefined
    var n = 100
    // Uncaught ReferenceError: Cannot access 'n2' before initialization  
    //未捕獲引用錯誤:在初始化之前無法通路“n2”
    console.log(n2)
    let n2 = 200
    console.log(n3) //  Uncaught ReferenceError: Cannot access 'n3' before initi
    const n3 = 300
    
    // // 2. 變量重名
    var n = 100
    var n = 200
    console.log(n)
    //Uncaught SyntaxError: Identifier 'n1' has already been declared 
    //未捕獲的文法錯誤:辨別符“n1”已聲明
    let n1 = 100
    let n1 = 200 //會報錯 
    const n2 = 200
    const n2 = 300 //會報錯
    
    // 3. 塊級作用域
    if (true) {
        var n = 100
        console.log(n) //100
    }
    console.log(n) // 100
    if (true) {
        let n = 200
        console.log(n) //200
    }
    console.log(n) //Uncaught ReferenceError: n is not defined
    const n = 400
    if (true) {
        const n = 300
        console.log(n) //300
    }
    console.log(n) //400
</script>


複制代碼           

案例-頁籤

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .box {
      width: 500px;
      height: 320px;
      display: flex;
      flex-direction: column;
      margin: 50px auto;
      border: 3px solid #333;
    }

    .box > ul {
      height: 60px;
      display: flex;
    }

    .box > ul > li {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 30px;
      color: #fff;
      background-color: skyblue;
      cursor: pointer;
    }

    .box > ul > li.active {
      background-color: orange;
    }

    .box > ol {
      flex: 1;
      position: relative;
    }

    .box > ol > li {
      width: 100%;
      height: 100%;
      background-color: purple;
      font-size: 50px;
      color: #fff;
      position: absolute;
      left: 0;
      top: 0;
      display: none;
    }

    .box > ol > li.active {
      display: block;
    }
  </style>
</head>
<body>

  <div class="box">
    <ul>
      <li class="active">1</li>
      <li>2</li>
      <li>3</li>
    </ul>
    <ol>
      <li class="active">1</li>
      <li>2</li>
      <li>3</li>
    </ol>
  </div>


  <script>
    /*
      案例 - 頁籤
    */

    for (let i = 0; i < btns.length; i++) {
      btns[i].onclick = function () {
        for (let j = 0; j < btns.length; j++) {
          btns[j].classList.remove('active')
          boxs[j].classList.remove('active')
        }

        btns[i].classList.add('active')
        boxs[i].classList.add('active')
      }
    }

    /*

  </script>
</body>
</html>
           

ES6箭頭函數

●箭頭函數是ES6 文法中定義函數的一種新方式

●箭頭函數隻能用來定義函數表達式,是以箭頭函數也是匿名函數

●當你把函數當做一個值指派給另一個内容的時候, 叫做函數表達式

●聲明式函數的定義方式是不能定義箭頭函數的

○function fn() {} 這樣的方式是聲明式函數,不能用來定義箭頭函數

●文法:() => {}

○()中書寫形參

○{}中書寫代碼片段

箭頭函數的特點

●可以省略小括号不寫

○當你的形參隻有一個的時候, 可以不寫小括号

○如果你的形參沒有或者兩個及以上, 必須寫小括号

<script>
    let fn1 = () => {
        console.log('我是 fn1 函數, 我沒有形參')
    }
    fn1()
        // 一個形參, 可以不寫小括号
    let fn2 = a => {
        console.log('我是 fn2 函數, 有一個參數', a)
    }
    fn2(10)
        // 兩個形參, 必須寫小括号
    let fn3 = (a, b) => {
        console.log('我是 fn3 函數, 有兩個參數', a, b)
    }
    fn3(100, 200)
</script>


複制代碼           

●可以省略大括号不寫

○當的代碼隻有一句話的時候, 可以省略大括号不寫, 并且會自動傳回這一句話的結果

○否則, 必須寫你大括号

<script>
    let fn1 = (a, b) => a + b
    let res = fn1(10, 20)
    console.log(res) //30
    var arr = [1, 2, 3, 4, 5, 6, 7]
    //演變過程
    // var res = arr.filter(function (item) { return item % 2 })
    // var res = arr.filter((item) => { return item % 2 })
    // var res = arr.filter(item => { return item % 2 })
    var res1 = arr.filter(item => item % 2)
    console.log(res1) //[1, 3, 5, 7]
</script>


複制代碼           

●箭頭函數中沒有arguements

○箭頭函數内天生不帶有 arguments。沒有所有實參的集合

<script>
    //普通函數
    let fn1 = function() {
        console.log(arguments)//會拿到傳遞的實參  
    }
    fn1(10, 20, 30, 40, 50)
    //箭頭函數
    let fn2 = () => {
        console.log(arguments)//會報錯
    }
    fn2(10, 20, 30)
</script>


複制代碼           

●箭頭函數内沒有this

○箭頭函數中的this指向外部作用域

○也就是書寫在箭頭函數的外面那個函數 this 是誰, 箭頭函數内的 this 就是誰

<script>
    var obj = {
        name: '我是 obj 對象',
        f: function() {
            console.log('f : ', this) //Object
        },
        f2: () => {
            // 這裡沒有 this, 用的是 外部的 this
            console.log('f2 : ', this) //Window
        }
    }
    obj.f()
    obj.f2()
</script>
           

繼續閱讀