如何从JavaScript文件中获取方法名称 [英] How to get method name from JavaScript file

查看:93
本文介绍了如何从JavaScript文件中获取方法名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript文件,其中定义了许多方法。有没有办法知道该文件中有多少方法&方法的名称是什么?

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?

推荐答案

简短的回答是不。

长的答案是,如果JS文件是你的 JS文件,即你控制内容,那么有几种方法可以构建代码,让你获得一个计数或功能名称列表。显然,这对你的其他人的代码没有帮助。如果您已经知道所有这些,请道歉,但是如果您不知道:通常最好将所有库函数作为单个对象的属性包装起来,如下所示:

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.
}

这会创建一个名为 myFunctionLibrary 的全局变量,它是一个具有属性引用的对象。 (注意:还有其他几种方法可以实现类似的效果,我更喜欢这种方式,但这对于这种解释来说似乎最简单。)然后,您可以通过以下方式访问这些函数:

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.

这篇关于如何从JavaScript文件中获取方法名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆