开发者

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

开发者 https://www.devze.com 2023-01-19 19:59 出处:网络
Consider the following sample: var Container = function(param) { this.member = param; var privateVar = param;

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

精彩评论

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