I have a JavaScript file with many methods defined in it. Is there any way to know how many methods are in that file & what are the names of methods?
The short answer is "no".
The long answer is that if the JS file is your JS file, i.e., you control the content, then there are several ways that you can structure the code that will let you obtain a count or list of function names. Obviously that won't help you with other people's code. Apologies if you already know all of this, but just in case you don't: it's generally a good idea to wrap all of your "library" functions up as properties of a single object, something like this:
var myFunctionLibrary = {
doSomething : function() {},
somethingElse : function() {},
nonFunctionProperty : "test",
// etc.
}
This creates a single global variable called myFunctionLibrary
, which is an object with properties that are references to functions. (Note: there are several other ways to achieve a similar effect, ways that I prefer over this way, but this seems simplest for purposes of this explanation.) You then access the functions by saying:
myFunctionLibrary.doSomething();
// or
myFunctionLibrary["doSomething"]();
Because all of your functions are then contained in a specific object you can iterate over them like any other object:
var funcCount = 0;
var propCount = 0;
for (fn in myFunctionLibrary) {
if (typeof myFunctionLibrary[fn] === "function"){
funcCount++;
alert("Function name: " + fn);
} else {
propCount++;
}
}
alert("There are " + funcCount + " functions available, and "
+ propcount + " other properties.");
The main advantage, though, is that you don't have to worry about your functions potentially having the same names as functions in some other library that you want to use.