tags:

views:

420

answers:

5

I created a Javascript Obj, but how can I get back the Class of that Javascript Obj?

I want something that similar to Java .getClass() method.

+4  A: 

There's no exact counterpart to Java's #getClass() in JavaScript. Mostly that's due to JavaScript being a prototype-based language, as opposed to Java being a class-based one.

Depending on what you need #getClass() for, there are several options in JavaScript:

A few examples:

function Foo() {}
var foo = new Foo()

typeof(foo) // == "object"

foo instanceof Foo // == true
foo.constructor // == Foo

Foo.prototype.isPrototypeOf(foo) // == true
Foo.prototype.bar = function (x) {return x+x}
foo.bar(21) // == 42
earl
That should probably be `func.prototype` (yes, functions are objects, but the `prototype` property is only relevant on function objects).
Miles
Yes, good point.
earl
you might also want to mention `instanceof`/`isPrototypeOf()` and the non-standard `__proto__`
Christoph
ES5 has aditionally `Object.getPrototypeOf()`
Christoph
For me, foo.constructor yields something different (Chrome 8.0.552.0 dev on Mac OS X): `Function Foo() {}`
clarkf
Yes, clarkf, that's `Foo` pretty-printed. The comments don't indicate the return values, but equalities that hold for the return values. So the comment means that `foo.constructor == Foo` holds, which will also be the case for you.
earl
A: 

Javascript is a class-less languages: there are no classes that defines the behaviour of a class statically as in Java. JavaScript uses prototypes instead of classes for defining object properties, including methods, and inheritance. It is possible to simulate many class-based features with prototypes in JavaScript.

dfa
I have often said that Javascript lacks class :)
shambleh
+1  A: 

You can get a reference to the constructor function which created the object by using the constructor property:

function MyObject(){
}

var obj = new MyObject();
obj.constructor; // MyObject

If you need to confirm the type of an object at runtime you can use the instanceof operator:

obj instanceof MyObject // true
CMS
A: 

In javascript, there are no classes but i think you whant the constructor name so obj.constructor.toString() will tell you what you need.

Jikhan
A: 

This function returns either "undefined", "null", or the "class" in [object class] from Object.prototype.toString.call(someObject).

function getClass(obj) {
  if (typeof obj === "undefined")
    return "undefined";
  if (obj === null)
    return "null";
  return Object.prototype.toString.call(obj)
    .match(/^\[object\s(.*)\]$/)[1];
}

getClass("")   === "String";
getClass(true) === "Boolean";
getClass(0)    === "Number";
getClass([])   === "Array";
getClass({})   === "Object";
getClass(null) === "null";
// etc...
Eli Grey