javascript 関数の呼び出し元の関数の名前を取得する
- 2020.08.27
- javascript
- javascript

javascriptで2020年の段階で非推奨になってるcaller.nameを使用して、関数の呼び出し元の関数の名前を取得するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
caller.name使い方
caller.nameを使うと、関数の呼び出し元の関数の名前を取得することができます。
1 |
呼び出される関数名.caller.name |
サンプルコード
以下は、それぞれのボタンをクリックして、fooという名称の関数の呼び出した関数を表示するサンプルコードとなります。
※cssには「bootstrap material」を使用してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"> <link rel="stylesheet" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css" integrity="sha384-wXznGJNEXNG1NFsbm0ugrLFMQPWswR3lds2VeinahP8N0zJw9VWSopbjv2x7WCvX" crossorigin="anonymous"> </head> <style> .main { margin: 0 auto; margin-top: 150px; display: flex; flex-direction: column; align-items: center; font-size: 20px; } </style> <script> function hoge() { foo(); } function foo() { // 呼び出し元の関数を表示 } </script> <body> <div class="main"> <div class="alert alert-primary" role="alert"> 呼び出した関数名 </div> <button type="button" class="btn btn-raised btn-primary" onclick="hoge()">関数内でfoo実行</button> <button type="button" class="btn btn-raised btn-success" onclick="foo()">onclickでfoo実行</button> </div> </body> </html> |
呼び出し元の関数名が表示されていることが確認できます。

-
前の記事
javascript 三項演算子を使ってif文を1行で書く 2020.08.27
-
次の記事
docker-composeを利用してredmineを構築する 2020.08.28
コメントを書く