As this was already answered, I just wanted to point out the differences in approaches on getting the constructor of an object in JavaScript.
There is a difference between the constructor and the actual object/class name. If the following adds to the complexity of your decision then maybe you're looking for instanceof
. Or maybe you should ask yourself "Why am I doing this? Is this really what I am trying to solve?"
Notes:
The obj.constructor.name
is not available on older browsers.
Matching (\w+)
should satisfy ES6 style classes.
Code:
var what = function(obj) {
return obj.toString().match(/ (\w+)/)[1];
};
var p;
// Normal obj with constructor.
function Entity() {}
p = new Entity();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));
// Obj with prototype overriden.
function Player() { console.warn('Player constructor called.'); }
Player.prototype = new Entity();
p = new Player();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));
// Obj with constructor property overriden.
function OtherPlayer() { console.warn('OtherPlayer constructor called.'); }
OtherPlayer.constructor = new Player();
p = new OtherPlayer();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));
// Anonymous function obj.
p = new Function("");
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));
// No constructor here.
p = {};
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));
// ES6 class.
class NPC {
constructor() {
}
}
p = new NPC();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));
// ES6 class extended
class Boss extends NPC {
constructor() {
super();
}
}
p = new Boss();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));
Result:
Code: https://jsbin.com/wikiji/edit?js,console
Update: Dec 04, 2023
For those needing to grab the class name in IE6 and IE8, obj.constructor
exists but name
property doesn't exist. So you need to call what(obj.constructor)
.