0

I am learning javascript and the following code confuses me.

//a constructor function
function Person() {
}

//creating object person1
var person1 = new Person();

//changing the prototype of Person
Person.prototype = {};

//creating object person2
var person2 = new Person();

Now, person1.constructor still remains function Person(), whereas person2.constructor gives function Object().

If I understand correctly, person1.constructor works by person1.__proto__.constructor and person1.__proto__ points to Person.prototype

In this case, shouldn't person1.constructor be function Object() instead of function Person()?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    Well, `person1.__proto__` points to the value `Person.prototype` had **before** you assigned a new value to it. And at that point (before the reassignment) `Person.prototype.constructor` referenced `Person`. If you do `person1.__proto__ === person2.__proto__` you will get `false`, meaning both instances have different prototypes. – Felix Kling Feb 27 '17 at 03:17
  • 1
    The internal `[[Prototype]]` is set when the instance is created. Changing the constructor's prototype to a different object later doesn't change existing instances (which seems to be the point of the code). ;-) – RobG Feb 27 '17 at 03:19
  • Thanks guys for the reply, I read the other post RobG has mentioned. Its clear to me now. – user3537195 Feb 27 '17 at 04:05

0 Answers0