Confusing behavior of instanceof

I’m trying to understand the difference between declaring a variable (using constructor function) before and after the prototype modification. Here’s my code:

function Cat(breed) {
this.breed = breed;

let beforeMimi = new Cat("persian");

console.log(beforeMimi instanceof Cat)  		// true
console.log(afterMimi instanceof Cat)  		// false

Cat.prototype = {
	 eat: 'nomnom',
	 drink: 'gugut'

let afterMimi = new Cat("persian");

console.log(beforeMimi instanceof Cat)  		// false
console.log(afterMimi instanceof Cat)  		// true

The instance beforeMimi was created before the prototype update; whereas the instance afterMimi was created after the prototype upate. My question is why did the four instanceof's return such contrasting output?

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36 Edg/93.0.961.52

Challenge: Remember to Set the Constructor Property when Changing the Prototype

Link to the challenge:

Here the difference may have less to o with prototype modification than you think.

Let us examine your first two console.log():
At this point, you have declared beforeMimi, there has been no prototype modifications to the Cat class, so we can reasonably assume that beforeMimi instanceof Cat == true.
However, at this point you have not declared the variable afterMimi, and you can verify that console.log(afterMimi) would print undefined to the console. Therefore afterMimi instanceof Cat == false, afterMimi doesn’t even exist yet.

Let’s see the next 2 console.log():
At this point, beforeMimi exists, but using an old prototype of Cat, which you have updated. Therefore we can reasonably expect beforeMimi instanceof Cat to no longer be true.
However afterMimi was created with the prototype change, it is of the new Cat class, and therefore afterMimi instanceof Cat == true

TLDR: first time you log afterMimi it doesn’t exist

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.