Reputation: 1140
In the example below:
var A = function() {};
var a = new A();
var b = new A();
A.prototype.member1 = 10;
A.prototype = {}
var c = new A();
Now the a.constructor
and b.constructor
are both pointing to function A
, which is expected.
However, c.constructor
is pointing to a void object
.
What is the rationale behind this? Thanks.
Upvotes: 0
Views: 47
Reputation: 147403
Now the a.constructor and b.constructor are both pointing to function A, which is expected. However, c.constructor is pointing to a void object. a and b both have the original A.prototype object as their internal
[[Prototype]]
, which has a constructor property referencing A. So when you do:What is the rationale behind this? Thanks.
a.constructor
it is the inherited constructor property that is used.
You then replace the original prototype object with a new, "empty" object that doesn't have a constructor property. Replacing the constructor's prototype does not change the internal [[Prototype]]
of existing instances, they still reference the object that was the prototype at the time they were constructed.
The new object will only be used as the [[Prototype]]
for new instances, so when you construct c, it's internal [[Prototype]]
is this new object that has no constructor property, so it continues along the [[Prototype]]
chain until a constructor property is found on Object.prototoype, which references the Object constructor.
var A = function() {};
var a = new A();
var b = new A();
A.prototype.member1 = 10;
// Replace A.prototype
A.prototype = {}
var c = new A();
// a still uses original prototype, so inherits member1
console.log(a.member1); // 10
// c uses the plain object, so doesn't have member1 property
console.log(c.member1); // undefined
// c inherits constructor property from Object.prototype, so
// references Object constructor
console.log(c.constructor === Object); // true
Upvotes: 1