これはすでに回答されているので、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