javascript lodashを使って親クラスを含まず関数名を配列で取得する
- 作成日 2021.12.28
- 更新日 2022.05.13
- javascript lodash
- javascript, lodash

javascriptで、lodashを使って親クラスを含まず関数名を配列で取得するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- lodash 4.17.21
- ブラウザ chrome 101.0.4951.54
lodash使用
こちらのサイトから最新版を確認して、CDN版を使用してます。
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

親クラスを含まず関数名を配列で取得
親クラスを含まず関数名を配列で取得するには、「_.functions」を使用します。
'use strict';
function Hoge() {
this.a = () => 1;
this.b = () => 2;
}
// 親を作成
Hoge.prototype.c = () => 3;
// 親クラスを含まない
console.log(
_.functions(new Hoge) // ["a", "b"]
)
実行結果を確認すると、配列で関数名が取得されていることが確認できます。

サンプルコード
以下は、
「実行」ボタンをクリックして、親クラスを含まず関数名を配列で取得するサンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
</head>
<script>
function Foo() {
this.a = () => 1;
this.b = () => 2;
}
// 親を作成
Foo.prototype.c = 3;
const hoge = () => {
disp(_.functions(new Foo), 'foo')
}
const disp = (arr, id) => {
let text = [];
arr.forEach((x, i) => text.push('<li class="list-group-item">' + arr[i] + '</li>'))
document.getElementById(id).innerHTML = text.join('');
}
window.onload = () => {
btn.onclick = () => { hoge() }
}
</script>
<body>
<div class="container mx-auto my-56 w-1/3 px-4">
<div id="sample" class="flex flex-col justify-center">
<h1 id="bar" class="font-semibold text-blue-500 text-lg mr-auto">実行結果</h1>
<ul id="foo" class="font-semibold text-gray-500 text-lg mr-auto"></ul>
<button id="btn"
class="mb-2 md:mb-0 bg-transparent hover:bg-blue-300 text-blue-700 font-semibold hover:text-white py-2 px-4 border border-blue-300 hover:border-transparent rounded">
実行
</button>
</div>
</div>
</body>
</html>
実行結果を確認すると、結果が表示されていることが確認できます。

-
前の記事
Hasura テーブルを追加する 2021.12.28
-
次の記事
MySQL マルチバイト文字(日本語の全角文字等)の文字コードを取得する 2021.12.28
コメントを書く