【问题标题】:How to list the functions/methods of a javascript object? (Is it even possible?)如何列出 javascript 对象的函数/方法? (这甚至可能吗?)
【发布时间】:2011-05-20 04:11:33
【问题描述】:

故意将这个问题表述为this question

我什至不知道这是否可能,我记得模糊地听说过一些关于 JS 中不可枚举的属性。

总之,长话短说:我正在一个 js 框架上开发一些东西,我没有文档,也无法轻松访问代码,这将极大地帮助我了解我可以用我的对象做什么。

【问题讨论】:

    标签: javascript methods scope member-functions


    【解决方案1】:

    如果您在项目中包含Underscore.js,则可以使用_.functions(yourObject)

    【讨论】:

      【解决方案2】:

      我想这就是你要找的:

      var obj = { locaMethod: function() { alert("hello"); }, a: "b", c: 2 };
      for(var p in obj)
      {
          if(typeof obj[p] === "function") {
            // its a function if you get here
          }
      }
      

      【讨论】:

        【解决方案3】:

        您应该能够枚举直接在对象上设置的方法,例如:

        var obj = { locaMethod: function() { alert("hello"); } };
        

        但大多数方法都属于对象的原型,如下所示:

        var Obj = function ObjClass() {};
        Obj.prototype.inheritedMethod = function() { alert("hello"); };
        var obj = new Obj();
        

        所以在这种情况下,您可以通过枚举 Obj.prototype 的属性来发现继承的方法。

        【讨论】:

        • 这是我在实践中遇到的问题。我会得到我的对象中的所有东西,但不是 Obj.prototype,然后如果我记得,把我的代码放在这里作为答案。我认为这是自省。这个还有别的说法吗?
        【解决方案4】:

        您可以使用以下内容:

        var obj = { locaMethod: function() { alert("hello"); }, a: "b", c: 2 };
        
        
        for(var p in obj)
        {
            console.log(p + ": " + obj[p]); //if you have installed Firebug.
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多