# 箭頭函式 arrow function|筆記 by Sz ###### tags: `Sz` `課前` `Vue新手夏令營` - [Vue 新手夏令營 課程頁面](https://hackmd.io/@dbFY0UD9SUeKmNXhWf01ew/BkJoW-hn_/%2FC05go-8iTSS-nrMwKU22kA) - [:sun_with_face:筆記入口](/2JiZbCPdR0G4p5fNycPmTg) :::info ``` ( (parameter) => {<自帶 return>}) ``` - **Arrow Function 的特性** - `()`: parameter 若只有一個的話,可省略 - `{}`: 只有一行的話,可省略 - 自帶 `return` - 本身無自己的 `this` 指向,看外層 ::: ## 箭頭函式的 this 指向 - 沒有自己的 this,看上層 function 的 this 是誰 - 沒有上層 function 那就是看全域 ### 先複習傳統的 function 裡的 this - this 是指看呼叫時,是誰呼叫這個 function 的 - callback function 通常是在全域下被呼叫的 ``` var name = '全域' const person = { name: '小明', callName: function () { console.log('1', this.name); // 1 小明 setTimeout(function () { console.log('2', this.name); // 2 全域 console.log('3', this); // 3 window }, 10); }, } person.callName(); ``` ### 箭頭函式裡面出現 this 箭頭函式內的 this 跟等同於**包住他的外層 function** 的 this ``` var name = '全域' const person = { name: '小明', callName: function () { console.log('1', this.name); // 1 小明 setTimeout (() => { console.log('2', this.name); // 2 跟外層的 this.name 一樣都是小明 console.log('3', this); // 3 跟外層的 this 一樣都是 person }, 10); }, } person.callName(); ``` ## 沒有被 function 包住的箭頭函式 沒有上層 function 那就是看全域 ``` var name = '全域' const person = { name: '小明', callName: () => { console.log(this.name); // 沒有外部 function 參考,this 會指向全域 }, } person.callName(); ``` ## 上章[this 的幾種狀況]([/Ngdg5j1RTDy5l__Sa-UTqQ](https://hackmd.io/Ngdg5j1RTDy5l__Sa-UTqQ#this-%E7%9A%84%E5%B9%BE%E7%A8%AE%E7%8B%80%E6%B3%81))指向不如預期的話題 - 先讓 this 在外層設定指向其他變數:vm (Vue 中指的 ViewModel) - 使用箭頭函式 ### 先讓 this 設定指向其他變數:vm 在 function 外面抓取外部的 vm 再將 vm 帶進去 function 內部 ``` var obj4 = { someone: '物件 4', fn() { const vm = this; // vm 在 Vue 中意指 ViewModel setTimeout(function () { console.log(this.someone); }); } } obj4.fn(); ``` ### 直接改用箭頭函式 用箭頭函式的特性,會直接讀取外層的 this ``` var obj4 = { someone: '物件 4', fn() { setTimeout(() => { console.log(this.someone); }); } } obj4.fn(); ```