Wrong info provided

After reading doc related to setting prototype to new object will give wrong results for constructor property and we should use instanceof to verify type of object but i am seeing that instanceof is giving wrong result but constructor property is giving right result.

function Bird(name) {
  this.name = name;  //own property
}
let r = new Bird("f"); 
r instanceof Bird 
// true
r.constructor === Bird 
// true
 Bird.prototype = {};
r.constructor === Bird
// true
r instanceof Bird 
// false
1 Like

which lesson is this one I want to go and check it

I think you are not understanding the question … we don’t use the instanceOf …here we are defining the constructor property so that whenever a prototype is set manually to a object it doesn’toverwritten

I’ll try to walk through it step by step, but prepare to be confused:

  1. Defining a constructor function:
function Bird(name) {
  this.name = name;
}
  1. Setting the prototype-to-use when a new object is created with this constructor function:
Bird.prototype = {
  constructor: Bird,
  numLegs: 2
};
  1. Creating a new object:
let r = new Bird("f");

At this point, you can log whether r is an instance of Bird:

r instanceof(Bird) //true

That is the same as the following (what’s the instanceof method is doing under the hood):

Object.getPrototypeOf(r) === Bird.prototype //true

  1. Set Bird.prototype to an empty object:
Bird.prototype = {};

If you now use the instanceof method, it’ll return false, because:

/* This is still pointing at the object that we've defined under 2)  */
console.log(Object.getPrototypeOf(r))

/* This is pointing at a new empty object */
console.log(Bird.prototype)

And the reason why r.constructor is true even if you overwrite the Bird.prototype object: Because you’ve also defined that under 2). Writing it a little differently:

Bird.prototype.constructor = Bird

It’s a bit brain-frying, but changing Bird.prototype to an empty object will not erase what r.constructor points at. It still points at the Bird function.

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