Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

reflection - Is it possible to reflect the arguments of a Javascript function?

Is it possible to get all of the arguments a Javascript function is written to accept? (I know that all Javascript function arguments are "optional")? If not, is it possible to get the number of arguments? For example, in PHP, one could use:

$class = new ReflectionClass('classNameHere');
$methods = $class->getMethods();
foreach ($methods as $method) {
    print_r($method->getParameters());
}

... or something like that, I haven't touched PHP in a while so the example above may not be correct.

Thanks in advance!

EDIT: Unfortunately, I have to be able to get the arguments outside of the body of the function... Sorry for the lack of clarification, but thanks for the current answers!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This new version handles fat arrow functions as well...

args = f => f.toString ().replace (/[
s]+/g, ' ').
              match (/(?:functions*w*)?s*(?:((.*?))|([^s]+))/).
              slice (1,3).
              join ('').
              split (/s*,s*/);

function ftest (a,
                 b,
                 c) { }

let aftest = (a,
                 b,
                 c) => a + b / c;

console.log ( args (ftest),  // = ["a", "b", "c"] 
              args (aftest), // = ["a", "b", "c"]
              args (args)    // = ["f"]
             );

Here is what I think you are looking for :

 function ftest (a,
                 b,
                 c) { }
 var args = ftest.toString ().
              replace (/[
s]+/g, ' ').
              match (/functions*w*s*((.*?))/)[1].split (/s*,s*/);

args will be an array of the names of the arguments of test i.e. ['a', 'b', 'c']

The value is args will be an array of the parameter names if the ftest is a function. The array will be empty if ftest has not parameters. The value of args will be null if ftest fails the regular expression match, i.e it is not a function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...