iT邦幫忙

1

Javascript 進階 9-3 常見問題

這一篇教學要來探討的是關於箭頭函式的常見問題

以下會列出幾個比較常見的問題來討論~

1. 回傳的問題

我們先前有說過,當我們想要箭頭函式直接回傳一個值的時候,可以省略大括號{},直接指向該值:

const arrFn = () => 1;

console.log(arrFn());

https://ithelp.ithome.com.tw/upload/images/20200520/20121770J4F4SGO6o9.png

很明顯他會回傳 1 當作結果。

但如果我們今天要回傳一個物件的時候~

const arrFn = () => { data: 1 };

console.log(arrFn());

https://ithelp.ithome.com.tw/upload/images/20200520/20121770pyBfdB4J5e.png

他會說是 undefined ~原因在於這個物件的{}被當作是箭頭函式的Block,而非物件實字的外層。

要解決這樣的問題,只要再物件外層包上()就可以了!

const arrFn = () => ({ data: 1 });

console.log(arrFn());

https://ithelp.ithome.com.tw/upload/images/20200520/20121770s8fZidhlbH.png

2. 邏輯運算子的連用

let num = 0;

const numFn = num || function () { return 1; }

console.log(numFn());

以上的狀況我們知道 num 是 Falsy ,所以一定會回傳後面的函式,之後執行回傳的結果是 1 這樣應該沒甚麼問題~

https://ithelp.ithome.com.tw/upload/images/20200520/20121770taxe24eIJX.png

但如果改成箭頭函式的話呢?

let num = 0;

const numFn = num || () => 1;

console.log(numFn());

https://ithelp.ithome.com.tw/upload/images/20200520/20121770aL6SBTCtkZ.png

就會報錯!!

原因就在箭頭函式在接邏輯運算子的時候,一樣需要用 () 隔開。

let num = 0;

const numFn = num || (() => 1);

console.log(numFn());

https://ithelp.ithome.com.tw/upload/images/20200520/20121770MlYVsaINDs.png

千萬要注意喔!

3. This 的指向

雖然上一篇文章有提到,但是還是在特別提醒一次:

const person = {
    myName: '小明',
    callName: () => {
        console.log(this.myName);
    }
};

person.callName();

以這樣的狀況進行箭頭函式的調用,這個時候的 this 就會指向全域的物件 window。

https://ithelp.ithome.com.tw/upload/images/20200520/201217706u7dRxVNYF.png

所以要改善這樣的情況,只要把箭頭函式改成傳統函式就可以了~!

const person = {
    myName: '小明',
    callName: function () {
        console.log(this.myName);
    }
};

person.callName();

https://ithelp.ithome.com.tw/upload/images/20200520/201217701OuyzPi8Rg.png

而這樣的錯誤最常發生在跟框架一起使用的時候:(以Vue為例)

const app = new Vue({
    data: {
        num: 1
    },
    created: function () {
        // Vue 的元件生命週期一開始會執行的階段
        console.log(this.num);
    }
});

https://ithelp.ithome.com.tw/upload/images/20200520/20121770QhY4RxuvKs.png

這邊 created 如果是使用傳統函式的話,就可以正確的取到值,但是如果是使用箭頭函式的話則會取到 undefined 。

https://ithelp.ithome.com.tw/upload/images/20200520/20121770e3SpnvmQwy.png

4. 利用箭頭函式來做為原型鏈上的方法

甚麼意思呢,我們來看看實際上的程式碼~

const Fn = function (a) {
    this.name = a;
}

Fn.prototype.arrFn = () => {
    return {
        to: this,
        name: this.name
    }
}

const newInstance = new Fn('函式');
console.log(newInstance.arrFn());

https://ithelp.ithome.com.tw/upload/images/20200520/20121770sZBWzEBdMl.png

很明顯,雖然我們可以找到這個用箭頭函式新增的方法,執行起來也沒問題,但因為是箭頭函式,裡面 this 的指向還是指向到全域的物件 window 上,所以無法達到預期的效果。

最快的修正方法還是建議使用傳統函式替代

這篇文章就先介紹到這邊,如果沒有問題的話就繼續往下一篇文章邁進吧!汪汪~


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言