Questo article definisce instanceof come qui sotto:JavaScript: Ancora confuso dall'operatore instanceof
test operatoreinstanceof se un oggetto ha nella sua catena di prototipi proprietà prototipo di un costruttore.
Questa è una spiegazione giusta e la vita è stata buona fino a quando mi sono imbattuto in questo codice dal libro eloquente Javascript:
function TextCell(text) {
this.text = text.split("\n");
}
TextCell.prototype.minWidth = function() {
return this.text.reduce(function(width, line) {
return Math.max(width, line.length);
}, 0);
}
TextCell.prototype.minHeight = function() {
return this.text.length;
}
TextCell.prototype.draw = function(width, height) {
var result = [];
for (var i = 0; i < height; i++) {
var line = this.text[i] || "";
result.push(line + repeat(" ", width - line.length));
}
return result;
}
function RTextCell(text) {
TextCell.call(this, text);
}
RTextCell.prototype = Object.create(TextCell.prototype);
RTextCell.prototype.draw = function(width, height) {
var result = [];
for (var i = 0; i < height; i++) {
var line = this.text[i] || "";
result.push(repeat(" ", width - line.length) + line);
}
return result;
};
Creiamo un'istanza di RTextCell ed eseguire il sotto c
var rt = new RTextCell("ABC");
console.log(rt instanceof RTextCell); // true
console.log(rt instanceof TextCell); // true
Capisco perché l'output del 2 ° console.log è "true" - perché il costruttore TextCell fa parte della catena del prototipo.
Tuttavia il 1 ° console.log mi confonde.
Se si guarda il codice (decima riga dal basso), il prototipo di RTextCell viene aggiornato a un nuovo oggetto, il cui prototipo è impostato su TextCell.prototype.
RTextCell.prototype = Object.create(TextCell.prototype);
.
Guardando le istantanee di seguito, non si fa menzione del costruttore "RTextCell" nella catena di prototipi dell'oggetto "rt". Quindi, seguendo la definizione che ho menzionato all'inizio del mio post, l'output non dovrebbe essere falso? Perché restituisce un valore vero?
Ho letto anche this ma non mi ha aiutato a capire questo problema specifico.
Vedere di seguito le istantanee di rt, RTextCell, TextCell in questo ordine.
È una domanda davvero ben strutturata. Hai mostrato tutte le tue indagini precedenti, spero che tu ottenga ottime risposte. –
Oh! Dovrei aggiungere Ho controllato questo prototipo di catena nelle istantanee di cui sopra sia su Chrome 43.0.2357.65 che su Firefox 33.1.1. – Harish