Struggling to grasp the instanceof operator in Javascript?

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.

Answer №1

Although you do alter RTextCell.prototype, the modification occurs prior to creating any instances of RTextCell. Consider this contrasting scenario, where RTextCell.prototype is adjusted after an instance has already been instantiated using the original prototype:

var rt = new RTextCell();
RTextCell.prototype = somethingTotallyDifferent;
rt instanceof RTextCell; // false!

Upon the creation of rt, it holds true that

rt.__proto__ === RTextCell.prototype
. However, once alterations are made to RTextCell.prototype, this equality no longer stands.

The examination isn't about determining whether rt possesses the initial prototype property from RTextCell within its prototype chain. Instead, it's about verifying if the current value of RTextCell.prototype is currently present in the object's prototype chain. This statement will always ring correct for RTextCell instances since objects created by the RTextCell constructor invariably acquire the updated value of RTextCell.prototype in their prototype chain, without any subsequent modifications to RTextCell.prototype post instantiation commencement.

Answer №2

It is crucial to pay attention to the specific wording used. While you mention the constructor being part of the prototype chain, the original statement does not include this detail:

The instanceof operator checks if an object's prototype chain contains the prototype property of a constructor.

Therefore, when evaluating the expression rt instanceof RTextCell, it's essentially checking something along these lines (note that __proto__ is not universally supported):

var p = rt.__proto__;
while(p)
{
  if(p == RTextCell.prototype)
    return true;
  p = p.__proto__;
}
return false;

Even though the function RTextCell isn't directly referenced in the object structures mentioned above, the RTextCell.prototype object plays a role.

Answer №3

To determine whether obj is an instance of RTextCell, the code uses the instanceof keyword followed by RTextCell. This checks if RTextCell.prototype is in the prototype chain of obj, which it is because obj was created with new RTextCell. The fact that RTextCell.prototype's prototype is TextCell.prototype may be causing confusion, but it doesn't change the result.

Even though RTextCell.prototype is still an object after setting its prototype to TextCell.prototype using Object.create, this update just changes its prototype without removing RTextCell.prototype itself.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Jquery confirmation dialogue does not seem to be functioning properly within the Content Place Holder

I've encountered an issue with a JQUERY Confirm dialogue where it works perfectly fine until I place it on a page that is within a masterpage. The confirm alert pops up for a split second and disappears. window.onload = function() { $("#ehi").cli ...

javascript - Alternate text colors several times within specified color ranges

Seeking assistance with changing the text color multiple times from #627CA9 to #FFFFFF and vice versa. Here's what I've tried: function changeColor(id) { var x = document.getElementById(id); if (document.getElementById(id).style.color = " ...

Implement a formatter function to manipulate the JSON data retrieved from a REST API within the BootstrapVue framework

My bootstrap-vue vue.js v2.6 app is receiving JSON data from a REST API. The data structure looks like this: { "fields": [ { "key": "name", "label": "name", & ...

The HTML unit is unable to locate the form for unknown reasons. My suspicion is that it could be due to the presence of Angular

Struggling with using HTMLunit to login and upload a file. Successfully logged in but unable to locate the form, despite it being present on the HTML page. Here is the JAVA CODE snippet: public static void main(String[] args) { WebClient webClient = ...

Having trouble with adding a class on scroll?

My challenge is to extract the header from this website, by adding an additional class when the user scrolls at a position greater than 0. I thought it would be easy, but Java always presents problems for me. Here’s the code I came up with: <!DOCTY ...

Leverage the power of jQuery to manipulate video tags

Here's the challenge: I need to utilize a jQuery function to extract a URL from a link's REL attribute and then transfer it to a video element. The extraction process and transmission seem to be working smoothly. However, my struggle lies in act ...

iOS creates dynamic images with artifacts that appear on a generated and animated canvas

I am currently developing an HTML5 web application for WeChat, compatible with both iOS and Android devices, using only pure JavaScript without any third-party libraries like jQuery. The main feature of my app involves creating visually appealing animation ...

What is the method to advance the opposing line in the dynamic chart?

Here is the link to the code for a dynamic graph. I am struggling with keeping the red line updated and moving forward together with the blue line. I cannot figure out why the red line remains static in the dynamic graph. Any suggestions on how to solve t ...

Ways to eliminate space between column arrangement in Bootstrap

I've designed 3 cards containing 2 widgets each in the sidebar. To ensure responsiveness, I utilized bootstrap 4 column ordering. One problem is when the right column is larger than the left one in a row of 2 columns, there's an awkward space be ...

Displaying the current time and total time of a custom video player using Javascript

Currently, I'm in the process of creating an html5 video player and have incorporated javascript to update the current time as a fraction of the total time. The script I've written so far is as follows: function updateTime() { var curTime = ...

A JavaScript function that smoothly scrolls an element into view while considering any scrollable or positioned parent elements

I needed a function that could smoothly scroll a specific element into view with some intelligent behavior: If the element is a descendant of a scrollable element, I wanted the ancestor to be scrolled instead of the body. If the element is within a posit ...

Support for both Fetch API and XMLHttpRequest across browsers is imperative for seamless data retrieval and

Currently, I am diving into the world of ajax programming techniques. However, I recently discovered that the XMLHttpRequest is deprecated and now I must transition to using the Fetch API. The catch is, according to MDN, the Fetch API is still considered e ...

What is the method for retrieving hotels from a database based on their proximity to a specific set of latitude and longitude coordinates?

I have a database table with latitude, longitude, and hotel locations. I want to create a feature that will show hotels near a specific point defined by latitude and longitude. Code Snippet function findNearbyHotels() { $this->lo ...

The act of sending back Null from the Array.map() function

I've been attempting to retrieve data from a JavaScript object using the array.map() function. However, the result I'm receiving is null. I'm confused as to what the issue might be. Here's the object: export const Course = [ { co ...

Inheritance of Arrays in Java

Currently, I'm facing some challenges in understanding how to approach a specific problem. My task is to create a class that can store an array with four elements, each having a different method. For instance, the first element needs to inherit data ...

Integrating chat functionality with a structured data format

Considering creating a collaborative communication platform, I am contemplating whether to develop a comprehensive application in JavaScript with MVC architecture or utilize it solely for managing message delivery using Node.js and socketIO. Would it be m ...

Identify the index of a list item using a custom list created from buttons

When dealing with a dynamically built list like this: <ul id="shortcuts"> <li><input type="checkbox" value="false"/><button>foo</button><button>-</button></li> <li><input type="checkbox" value ...

Slideshow elements removed

I attempted to remove my links individually from the div id="wrapper", but unfortunately have encountered an issue while doing so: window.onload = function () { setInterval(function () { var wrapper = document.getElementById("wrapper"); var my_l ...

Having trouble grasping the concept of C++ inheritance?

Snippet of Code: class A { protected: int b; }; class B : public A { }; struct C : B { int call (const C&); }; class D : B { int call (const C&); }; int C::call (const C& c) { return c.b; } int D::call (const C& c ...

Submitting the Ajax form will result in the quantity of the product in the cart being updated while remaining on

Hello, I am using ajax to keep the user on the same page after submitting a form. If successful, I will use ajax load to load another page that displays the quantity of the product. However, I am facing an issue where each subsequent submit increases the q ...