0
0

アロー関数とは?

Last updated at Posted at 2024-02-22

アロー関数とは?

ES6 JavaScript のアップデートで導入されました。 これは、変数を宣言し利用するもうひとつの方法です。 アロー関数がもたらすメリットは次のとおりです。

  • より簡潔である
  • this が周辺のスコープからピックアップされる
  • 暗黙的な return

内容

アロー関数のここがすごい!!

  • 関数を短く書ける ※例①
  • thisを束縛しない ※例②

アロー関数 実用例①:関数を短く書ける

function() の場合

let normalFunc = function(x){
    console.log(x);
}
normalFunc('今までの関数');

アロー関数の場合

let arrowFunc = (x) => {
    console.log(x);
}
arrowFunc('アロー関数式');

アロー関数 実用 例②: thisを束縛しない

function() の場合

this.text = 'aaa';

function hoge() {
  console.log(this.text);
}

const obj = {
  text : 'bbb',
  func : hoge,
};

const obj_2 = {
  text : 'ccc',
  func : hoge,
};

obj.func(); // => 'bbb'
obj_2.func(); // => 'ccc'

アロー関数の場合

this.text = 'aaa';

const hoge = () => {
  console.log(this.text);
}

const obj = {
  text : 'bbb',
  func : hoge,
};

const obj_2 = {
  text : 'ccc',
  func : hoge,
};

obj.func(); // => 'aaa'
obj_2.func(); // => 'aaa'

結論

個人的にはFunctionを多用している為、なれるのが時間はかかるが

関数を短く書くことができる為、とても便利。

補足

アロー関数を使わずにthisを固定する場合  実用例③:bind(this)

//thisを通常した関数 -----------------------------------

var person = {
  name: 'mejileben',
  hobby: 'programming',
  callHobbyLater: function(){
    setTimeout(function(){
      console.log('趣味は' + this.hobby);
    },1000);
  },
  callName: function(){
    console.log("私の名前は" + this.name);
  }
}

person.callHobbyLater();//趣味はundefined ※ここがエラー(this)
                   
person.callName();//私の名前はmejileben

// bind(this)を使用した場合 -------------------------------------

var person = {
  name: 'mejileben',
  hobby: 'programming',
  callHobbyLater: function(){
    setTimeout(function(){
      console.log('趣味は' + this.hobby);
// ここにbind(this)を書いておくとthisを確定しておける
    }.bind(this),1000);
  },
  callName: function(){
    console.log("私の名前は" + this.name);
  }
}

person.callHobbyLater();//私の名前はmejileben
person.callName();//趣味はprogramming

参考

0
0
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
0
0