0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

function定義の関数とアロー関数との this の違い

Last updated at Posted at 2019-12-30

function定義の関数の this

定義された文脈中の object

アロー関数の this

関数それ自体

  • function定義の関数の this

以下の例では obj1this となっている。

const obj1 = {
  num: 123,
  fn: function() {
    console.log(this);
  }
}

obj1.fn()
// { num: 444, fn: [Function: fn] }
  • アロー関数の this
const obj2 = {
  num: 888,
  fn:()=>{
    console.log(this);
  }
};

obj2.fn()
// Object [global] {
//   global: [Circular],
//     clearInterval: [Function: clearInterval],
//     clearTimeout: [Function: clearTimeout],
//     setInterval: [Function: setInterval],
//     setTimeout: [Function: setTimeout] { [Symbol(util.promisify.custom)]: [Function] },
//     queueMicrotask: [Function: queueMicrotask],
//     clearImmediate: [Function: clearImmediate],
//     setImmediate: [Function: setImmediate] {
//     [Symbol(util.promisify.custom)]: [Function]
//   }
// }

開発における使い分け

基本的にアロー関数を使って、コードベース内で統一していく方がいい。

そうすることで、function定義の関数を使っていると、関数内で this から何か使いたいんだなという意図を伝えられる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?