代码之家  ›  专栏  ›  技术社区  ›  uzay95

如何测试Javascript对象是否具有具有给定名称的方法?

  •  1
  • uzay95  · 技术社区  · 15 年前

    考虑以下示例:

    var Container = function(param) {
        this.member = param;
        var privateVar = param;
        if (!Container.prototype.stamp) {  // <-- executed on the first call only
            Container.prototype.stamp = function(string) {
                return privateVar + this.member + string;
            }
        }
    }
    
    var cnt = new Container();
    

    有没有办法确定这个物体 cnt stamp 不知道它是从 Container ?

    Another Example

    2 回复  |  直到 15 年前
        1
  •  2
  •   Tomas    15 年前

    你可以测试是否存在 stamp 使用:

    if (cnt.stamp) ...
    

    或者你可以检查它是否是

    if (typeof cnt.stamp === 'function') ...
    
        2
  •  2
  •   AutomatedTester    15 年前

    你可以用 hasOwnProperty

    o = new Object();  
    o.prop = 'exists';  
    o.hasOwnProperty('prop');             // returns true  
    o.hasOwnProperty('toString');         // returns false  
    o.hasOwnProperty('hasOwnProperty');   // returns false