This article explains the concept of instanceof operator as follows:
The instanceof operator checks if an object has in its prototype chain the prototype property of a constructor.
All was well until I stumbled upon this code snippet from Eloquent 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;
};
Let's create an instance of RTextCell and run the following code:
var rt = new RTextCell("ABC");
console.log(rt instanceof RTextCell); // true
console.log(rt instanceof TextCell); // true
I understand why the second console.log returns "true" - because constructor TextCell is part of the prototype chain.
However, the first console.log result puzzles me.
Considering the line in the code where RTextCell prototype is updated to a new Object with TextCell.prototype set as its prototype:
RTextCell.prototype = Object.create(TextCell.prototype);
.
Examining the snapshots below, there is no reference to constructor "RTextCell" in the prototype chain of object "rt". So, based on the definition provided at the beginning of this post, shouldn't the output be false? Why does it return true?
I also went through this but it didn't clarify this specific issue for me.
Refer below for the snapshots of rt, RTextCell, TextCell respectively.