This article defines an instance as shown below:
The instanceof operator checks whether the object in its prototype has a property to bind to the constructor prototype property.
This fair explanation and life was good until I came across this code from the book "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 create an instance of RTextCell and execute below c
var rt = new RTextCell("ABC"); console.log(rt instanceof RTextCell); // true console.log(rt instanceof TextCell); // true
I understand why the output of the second console.log is "true" - because the TextCell constructor is part of the prototype chain.
However, the first .log console confuses me.
If you look at the code (line 10 below), the RTextCell prototype will be updated to a new object whose prototype is set to TextCell.prototype.
RTextCell.prototype = Object.create(TextCell.prototype); .
Looking at the pictures below, the RTextCell constructor is not mentioned in the prototype chain of the rt object. So, based on the definition that I mentioned at the beginning of my post, should the conclusion not be false? Why does it return the true value?
I also read this one , but did not help me understand this particular problem.
Below are snapshots of rt, RTextCell, TextCell in that order.



source share