uzay95
uzay95

Reputation: 16632

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 ?

Another Example

Upvotes: 1

Views: 243

Answers (2)

Tomas
Tomas

Reputation: 5143

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') ...

Upvotes: 2

AutomatedTester
AutomatedTester

Reputation: 22418

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  

Upvotes: 2

Related Questions