1
0

More than 1 year has passed since last update.

【JavaScript】書き方による関数の違いまとめ

Posted at

はじめに

JavaScriptでは、関数の定義方法が複数あります。
いつもなんとなくで書いていたのですが、調べてみると書き方によって少しづつ違いがあったのでまとめてみようと思います。

関数の定義方法4つ

関数の定義方法は以下4つです。

1. function命令で定義

.js
function getTaxIncludedPrice(price, tax) {
    return price + price * tax
} 

2. Functionオブジェクトを利用して定義

.js
const getTaxIncludedPrice = new Function('price', 'tax', 'return price + price * tax')

3. 関数リテラルで定義

.js
const getTaxIncludedPrice = function(price, tax) => {
    return price + price * tax
}

4. 関数リテラルで定義(アロー関数)

.js
const getTaxIncludedPrice = (price, tax) => {
    return price + price * tax
}

書き方による特徴

1.評価のタイミングの違い

●function命令
 コードを解析するタイミング(コードの実行よりも前)で関数を登録
●FUnctionオブジェクト、関数リテラル、アロー数
 コード実行時に評価

.js
getTaxIncludedPrice(100, 1)

function getTaxIncludedPrice(price, tax) {
    return price + price * tax
]

これは正常に実行される

.js
getTaxIncludedPrice(100, 1)

const getTaxIncludedPrice = functoin(price, tax) {
      return price + price * tax
}
.js
getTaxIncludedPrice(100, 1)

const getTaxIncludedPrice = new Function('price', 'tax', 'return price + price * tax')
.js
getTaxIncludedPrice(100, 1)

const getTaxIncludedPrice = (price, tax) => {
    return price + price * tax
}

これらは実行時未定義となるためエラー

2.変数のスコープの違い

●Functionオブジェクト
 グローバル変数
●functoin命令、関数リテラル、アロー関数
 ローカル変数

.js

const hoge = 'global'
function test() {
    const hoge = 'local'

    const test1 = function() {
        console.log(hoge)
    }

    const test2 = new Function('console.log(hoge)')
    
    test1()
    test2()
}

test()

実行結果
スクリーンショット 2023-01-19 22.13.06.png

3.コンストラクタを持つかどうかの違い

●コンストラクタを持つ
 function命令、関数リテラル、Functionオブジェクト
●コンストラクタを持たない
 アロー関数

.js
function hoge(){
    console.log('インスタンス化された')
}
 new hoge()
.js
const hoge = function{
    console.log('インスタンス化された')
}
 new hoge()
.js
const hoge = new Function('console.log("インスタンス化された")')
new hoge()

これらは可能。
インスタンス化された際に関数内の処理が実行されるため、コンソールには以下が表示される。
スクリーンショット 2023-01-19 22.42.57.png

下記リンクでコンストラクタについて分かりやすい説明がされていました。
https://note.affi-sapo-sv.com/js-constructor.php

4.その他 アロー関数におけるthisの固定

※執筆中

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