tags:

views:

485

answers:

2

Hey all, I am trying to test if the argument passed into my function is a class name so that I may compare it to other classes using instanceof.

For example:

function foo(class1, class2) {
  // Test to see if the parameter is a class.
  if(class1 is a class)
  {
    //do some kind of class comparison.
    if(class2 is a class)
    {
       if(class1 instanceof class2)
       {
          //...
       }
    }
    else
    {
       //...
    }
  }
  else
    //...
}

Is this possible? I am having trouble googleing an answer.

+3  A: 

JavaScript does not have classes. It has functions which, when used with new, can be used to produce object instances. Therefore, you really want to test if class2 is a function. There are numerous ways of accomplishing this; the current (1.3) implementation of isFunction() in jQuery looks like this:

isFunction: function( obj ) {
 return toString.call(obj) === "[object Function]";
},

...But see here for a rundown of the different methods: Best method of testing for a function in JavaScript?

Shog9
+8  A: 

There is really no such thing as a "class" in javascript -- everything is an object. Even functions are objects.

instanceof DOES work with functions though. Check out this link.

function Car(make, model, year)
{
  this.make = make;
  this.model = model;
  this.year = year;
}
var mycar = new Car("Honda", "Accord", 1998);
var a = mycar instanceof Car;    // returns true
var b = mycar instanceof Object; // returns true
thesmart
"everything is an object" - Not exactly. The Primitive types(number, string, bool, null and undefined) are not objects.
Andreas Grech