snippetjavascriptCritical
How to get a JavaScript object's class?
Viewed 0 times
objecthowclassjavascriptget
Problem
I created a JavaScript object, but how I can determine the class of that object?
I want something similar to Java's
I want something similar to Java's
.getClass() method.Solution
There's no exact counterpart to Java's
Depending on what you need
A few examples:
Note: if you are compiling your code with Uglify it will change non-global class names. To prevent this, Uglify has a
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
obj.constructor
func.prototype,proto.isPrototypeOf
A few examples:
function Foo() {}
var foo = new Foo();
typeof Foo; // == "function"
typeof foo; // == "object"
foo instanceof Foo; // == true
foo.constructor.name; // == "Foo"
Foo.name // == "Foo"
Foo.prototype.isPrototypeOf(foo); // == true
Foo.prototype.bar = function (x) {return x+x;};
foo.bar(21); // == 42Note: if you are compiling your code with Uglify it will change non-global class names. To prevent this, Uglify has a
--mangle param that you can set to false is using gulp or grunt.Code Snippets
function Foo() {}
var foo = new Foo();
typeof Foo; // == "function"
typeof foo; // == "object"
foo instanceof Foo; // == true
foo.constructor.name; // == "Foo"
Foo.name // == "Foo"
Foo.prototype.isPrototypeOf(foo); // == true
Foo.prototype.bar = function (x) {return x+x;};
foo.bar(21); // == 42Context
Stack Overflow Q#1249531, score: 1461
Revisions (0)
No revisions yet.