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.
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.
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:
typeof()
instanceof
func.
prototype
, proto
.isPrototypeOf
obj.
constructor
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
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.
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
In javascript, there are no classes but i think you whant the constructor name so obj.constructor.toString() will tell you what you need.
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...