FM牛鍵屋本舗

プログラマ(弱)の日々精進系ブログ

アロー関数

去年末からずっと渋川よしきさんのRealWorldHTTPという本を読んでるんですが、 なかなか読了できず。。。

FetchAPIのサンプルを拝読していたら、
見慣れぬ構文が…。

// (中略)
.then((response) => {
    return response.json();
})
// (後略)

lamdaっぽい…

ということで、調べてみたら
ECMA6からアロー関数というのが追加されたっぽいですね。
目的は二点。

  • 関数を短く記述
  • thisを束縛しない

ふむ。

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javascript">
    function myFunc(sub) {
      console.log(sub('aaaa'));
    }
    myFunc((str) => {return str + 'help';});

    // 別に戻り値を返さなくてもいいし、こういうことも出来る。
    var lamda = (val) => {console.log(val);}
    lamda('take me');

    // JSオブジェクトを返すときは()で囲む。構文の{}と区別つけるためかな
    var obj = () => {return ({hoge : 'moge'});}
    console.log(obj());

    // こうすることで、引数のJSオブジェクトのプロパティにアクセス出来る
    obj = ({hoge}) => {return hoge;}
    console.log(obj({hoge : 'Giant'}));
    
    // thisの束縛について
    // 本来、thisのスコープはレシーバになる。
    // => なんか違った気がする…
    function testThis() {
      console.log('[outer]' + this.name);
      var self = this;
      function inner() {
        console.log('[inner]' + this.name);
        console.log('[inner-self]' + self.name);
      }
      inner();
    }
    testThis.call({name : 'testThis'});

    // アロー関数ではthisは外側のthisになる
    function testThisLamda() {
      console.log('[outer]' + this.name);
      var self = this;
      var inner = () => {
        console.log('[inner]' + this.name);
      }
      inner();
    }
    testThisLamda.call({name : 'testThisLamda'});
  </script>
</head>
<body>
</body>
</html>
aaaahelp
arrow.html:8:7
take me
arrow.html:13:27
Object { hoge: "moge" }
arrow.html:18:5
Giant
arrow.html:22:5
[outer]testThis
arrow.html:27:7
[inner]
arrow.html:30:9
[inner-self]testThis
arrow.html:31:9
[outer]testThisLamda
arrow.html:38:7
[inner]testThisLamda
arrow.html:41:9