开发者

How can I test whether a Javascript object has a method with a given name?

Consider the following sample:

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();

Is there any way to determine whether the object cnt has a method named stamp without knowing that it is instantiated from Container ?

How can I test whether a Javascript object has a method with a given name?


You can test for the existence of stamp with:

if (cnt.stamp) ...

or you can check whether it is a function with

if (typeof cnt.stamp === 'function') ...


You can use hasOwnProperty

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜