When you create an object with a constructor it has a constructor property pointing to the constructor function:
var Foo = function(foo) {
this.foo = foo;
}
var myFoo = new Foo(123);
myFoo.constructor === Foo; // true
After creating this object I can change Foo.prototype ...
Foo.prototype.x = 'y';
... or reassign a new prototype object:
Foo.prototype = {
num: 99
};
myFoo.constructor === Foo; // still true
But if I create a new Foo object after assigning a new object to Foo.prototype its constructor suddenly points to Object:
var myBar = new Foo(321);
myBar.constructor === Foo; // false
myBar.constructor === Object; // wtf?!
Adding new properties to the prototype doesn't produce this effect, you have to do the assignment Foo.prototype = {...}.
I have no idea why creating a new prototype would affect the constructor property. I tested in Chrome, Firefox and Internet Explorer, all with the same result. Can anybody help me understand this?
console.dir(myFoo)andconsole.dir(myBar)and you will see. Note: Assigning a new value toFunc.prototypedoes not affect existing instances of that constructor. Just in the same asvar foo = 10; var bar = foo; bar = 5;won't setfooto5.