이것이 이미 답변되었으므로 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