0
0

More than 3 years have passed since last update.

通常関数とアロー関数の違い

Posted at

通常関数とアロー関数の記述

以下,二つの関数の記述法である.

//function 
function f(x) {
  return x + 1;
}

//arrow function 
const f = (x) => x + 1;

通常関数とアロー関数とでは参照するthisが異なる

JavaScriptでは,関数もconstructor同様にthisのオブジェクトを持つことができる.
このthisオブジェクトの参照先が通常関数とアロー関数とで異なる.

  • 通常関数:宣言元のオブジェクト
//////通常関数のthis//////
function test1 {
  this.param = 'test1' //JavaScriptでは関数の中に関数を持つことも可能

  function printParam () {
    console.log( this.param )
  }

  let object1 {
    param: 'object1',
    func: printParam(),
  }

  let object2 {
    param: 'object2',
    func: printParam(),
  }

  object1.func()
  object2.func()
}

test1()
出力
object1
object2
  • アロー関数:宣言時のスコープを持つオブジェクト
///////アロー関数///////
function test2 {
  this.param = 'test2' //JavaScriptでは関数の中に関数を持つことも可能

  function printParam () {
    console.log( this.param )
  }

  let object3 {
    param: 'object3',
    func: printParam(),
  }

  let object4 {
    param: 'object4',
    func: printParam(),
  }

  object3.func()
  object4.func()
}

test2()
出力
test2
test2
0
0
2

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