2017-06-24 4 views
-1

Ich habe eine cat, die von animal erbt.JavaScript Basistyp ist `instanceof` abgeleiteten Typ Konstruktor

Ich würde erwarten, dass die cat eine Instanz seines Konstruktors und der animal Konstruktor sein.

Die animal ist eine Instanz des cat Konstruktors obwohl.

var animal = {}; 
 

 
var cat = Object.create(animal); 
 

 
console.log('cat instanceof animal.constructor: ' + (cat instanceof animal.constructor)); 
 
console.log(' cat instanceof cat.constructor: ' + (cat instanceof cat.constructor)); 
 
console.log('animal instanceof cat.constructor: ' + (animal instanceof cat.constructor));

Warum ist die animal eine Instanz des cat?

+0

Versuchen 'console.log (cat.constructor, cat.constructor === animal.constructor);' – 4castle

+0

@ 4castle Danke, aber _why_ sind sie gleich? Ich verstehe nicht, wie mein abgeleiteter Typ und mein Basistyp denselben Konstruktor haben. – BanksySan

+0

'cat' hat seine' constructor' Eigenschaft nicht definiert. Wenn Sie versuchen, auf 'cat.constructor' zuzugreifen, wird der Konstruktorwert des Prototyps verwendet. – 4castle

Antwort

0

Der folgende Code könnte Ihnen helfen, dieses Konzept zu verstehen.

Es gibt einen Unterschied zwischen instanceof, typeof und constructor

  • instanceof: Prüfungen für die ganze Kette
  • Object.prototype.constructor: gibt eine Referenz auf das Objekt-Konstruktor Funktion, die die Instanz-Objekt erstellt
  • typeof: Rückgabe des Datentyps von dem, was in Frage kommt

Jetzt in Ihrem Fall: Check Kommentare

var animal = {}; //animal is an object 
//animal.constructor is a parent Object constructor function 

var cat = Object.create(animal); 
//cat is an object created using animal object 
//cat.constructor will also return parent Object constructor because. 
//To remember this just remember that right side of instanceof always needs to be callable (that is, it needs to be a function) 

console.log('cat instanceof animal.constructor: ' + (cat instanceof animal.constructor)); 
//this will return true as animal.constructor is nothing but parent Object constructor function and every object is instanceof that parent Object() 

console.log(' cat instanceof cat.constructor: ' + (cat instanceof cat.constructor)); 
//this will also return true for the same reason as mentioned above 

console.log('animal instanceof cat.constructor: ' + (animal instanceof cat.constructor)); 
//this also has the same reason 
+0

Ist diese Zeile korrekt? "' Constructor': gibt nur das zurück, was das Objekt erstellt hat ". Es scheint, dass dies nicht der Fall ist, da der "cat" -Konstruktor der "Object" -Konstruktor ist. – BanksySan

+0

Ich sollte es besser @BanksySan umformulieren –

Verwandte Themen