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?
Write a program to load your file into Rhino, and then inspect the dictionaries and see what you have.
While, in theory, you could try to find everything that matched the pattern:
function <name>(
You'd be missing out on a lot of other types of functions. See, Functions are really just objects in JavaScript. They can be assigned, shared, modified, and moved around. So, you'd also have to find these:
var <name> = function() {}
And these:
function returnFunc() {
return function() {...}
}
var <name> = returnFunc();
As well as these:
obj.member = new Function();
And a nearly infinite variety of similar function definitions.
So, the answer is, most likely you can't. Unless the code is extremely narrowly constructed.
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.
Is there any way to know that how many methods are there in Java Script & what is the names of method?
Read the source or the documentation (if there is any).
If you're looking for some kind of "list avaialble methods" function, there isn't one. Writing one would be the equivalent of writing a javascript parser and perhaps even compiler.
Good luck with that. :-)