18
15

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.

関数の引数名を取得する

Posted at

AngularJSのDIとかで利用されているやつです。

関数オブジェクトのtoString()メソッドがソースコードを返すので、それを利用します。

function getParams(func) {
    var source = func.toString()
        .replace(/\/\/.*$|\/\*[\s\S]*?\*\/|\s/gm, ''); // strip comments
    var params = source.match(/\((.*?)\)/)[1].split(',');
    if (params.length === 1 && params[0] === '')
        return [];
    return params;
}

関数のソースコードを正規表現使ってゴリゴリと処理します。

getParams(function() {}); // => []
getParams(function(a) {}); // => ['a']
getParams(function(a, b) {}); // => ['a', 'b']
getParams(function(a, /* 途中に改行があっても、、、 */
b) {}); // => ['a', 'b']

こんな感じで使えるはずです。

バグとかあったら教えて下さい。

18
15
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
18
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?