0

Let's say I have a function, and I need to check if it has a class method of a certain name. For example:

function Foo() {
    this.bar = function() {
        console.log("I am bar!");
    }
}

And I want to check if the Foo class actually has the bar method. I can create a new instance of Foo and then check it, I was just wondering if there was a better way to do this.

Luoruize
  • 579
  • 2
  • 7
  • 25
  • 2
    JS has no classes, what you have, is rather a construcor function, which does not contain `bar` property. – Teemu Jan 11 '15 at 17:28
  • 3
    If you're creating the properties in the constructor, then the only way to tell is to examine the code of the constructor. That obviously would get complicated if the constructor *conditionally* sets the properties. – Pointy Jan 11 '15 at 17:28

3 Answers3

6

I can create a new instance of Foo and then check it, I was just wondering if there was a better way to do this.

No, not if the method is added in the constructor as in your example. There's nothing to check until you create an instance. (Well, except the source code of the constructor function, as Pointy points out in a comment.)

If it were defined on Foo.prototype, it would be a different matter:

function Foo() {
}
Foo.prototype.bar = function() {
    console.log("I am bar!");
};

Then you could check by looking for Foo.prototype.bar.


Side note: Calling them "class methods" is likely to confuse people. In class-based OOP, a "class method" is usually one that's not specific to instances, as opposed to being one that's specific to instances but defined by the class. And of course, JavaScript doesn't have class-based OOP (it has prototypical OOP instead, even as of ES6 which adds more class-like trappings).

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

There is no method until you do:

var x = new Foo();

So, you will have to do that and then test:

if (typeof x.bar === "function")

If your code was using the prototype for the bar method, then you could test the prototype directly without constructing an object, but since the method is only created inside the constructor, you have to run the constructor in order to see it.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

TJ Crowder is correct in that you cannot examine the constructor to examine if the "class" Foo has a certain method. However, you can do this:

function Foo() { /* Constructor */ }
Foo.prototype.bar = function() { /* Whatever you want */ }

Then to test, you can simply do typeof Foo.prototype.bar === "function".

There are various advantages and disadvantages to this approach. (See Use of 'prototype' vs. 'this' in JavaScript?). If you really need to test if a certain constructor's instances will inherit a method, you can use the prototype approach.

Community
  • 1
  • 1
soktinpk
  • 3,778
  • 2
  • 22
  • 33