Оскільки на це вже відповіли, я просто хотів вказати на відмінності підходів щодо отримання конструктора об’єкта в JavaScript. Існує різниця між конструктором та фактичним іменем об’єкта / класу. Якщо наступне додає складності вашого рішення, то, можливо, ви шукаєте instanceof. Або, можливо, варто запитати себе "Чому я це роблю? Це справді те, що я намагаюся вирішити?"
Примітки:
obj.constructor.nameЧи не доступна на старих браузерах. Відповідність (\w+)повинна задовольняти класам стилів ES6.
Код:
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));
Результат:

Код: https://jsbin.com/wikiji/edit?js,console