जैसा कि यह पहले से ही उत्तर दिया गया था, मैं सिर्फ जावास्क्रिप्ट में किसी ऑब्जेक्ट के निर्माता को प्राप्त करने के दृष्टिकोण में अंतर को इंगित करना चाहता था। कंस्ट्रक्टर और वास्तविक वस्तु / वर्ग नाम के बीच अंतर है। यदि निम्नलिखित आपके निर्णय की जटिलता को जोड़ता है तो शायद आप खोज रहे हैं 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