LoginSignup
3
1

More than 5 years have passed since last update.

ES6アロー関数

Last updated at Posted at 2017-03-04

アロー関数

functionキーワード、ブロックの{}returnの省略

アロー関数
// ES5
var add = function(a, b) {
  return a + b;
};

// ES6
var add = (a, b) => {
  return a + b;
};

var add = (a, b) => a + b;

var square = n => n * n;

[1, 2, 3, 4].filter(n => n% 2 === 0).map(n => n * n);

http://es6-features.org/#ExpressionBodies
http://es6-features.org/#StatementBodies

アロー関数のthisの補足

アロー関数を定義したコンテキストでthisを補足する。
ES5の場合、setTimeout関数の引数に指定された無名関数の内部ではthisがグローバルオブジェクトを指してしまうので、外側で一度thisをself変数に保存、もしくはbindメソッドによってthisを束縛する必要がある。

アロー関数を使うとthisは自動的に補足されるため、selfやbindを自分で書く必要がない。

thisの補足
// ES5
var john = {
  name: "John",
  helloLater: function() {
    // this (john) を保存しておく
    var self = this;
    setTimeout(function() {
      // ここでのthisはjohnではないのでselfを使う
      console.log("Hello, I'm " + self.name);
    }, 1000);

  }
}
john.helloLater();
// 「"Hello, I'm John"」が1秒後に表示される

// ES6
var john = {
  name: "John",
  helloLater: function() {
    // アロー関数を使うと、
    setTimeout(() => {
      // ここでのthisはjohnなのでそのまま使える
      console.log("Hello, I'm " + this.name);
    }, 1000);
  }
}

参考

WEB+DB PRESS vol.87 ECMAScript6特集

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1