I'm trying to understand how prototype and constructor work in JavaScript and came across this case.
I always picture how objects got created in JavaScript is by
- an empty object is created
- the object is linked to the function's prototype
- the object searches for a constructor function
- this constructor function got run and properties got assigned to that object
- the object is returned by an implicit
return this
This way of understanding seems not to be able to explain obj2
and obj3
.
For instance, I explicitly set Foo.prototype.constructor
to something else for obj2
, but obj2
still has the property bar
. Let's say bar
is stored in Foo's prototype, that explains why obj2
has the property bar
and why obj3
is created by Object
, but what if I create a couple more obj2
s, that would mean they share the same variable bar
on Foo's prototype, and I think this is not the case.
Can somebody give a more reasonable explanation on why obj2
and obj3
are like this?
function Foo(){
this.bar = true;
}
console.log('obj1');
var obj1 = new Foo();
console.log(obj1);
console.log(obj1.constructor === Foo);
console.log('obj2');
Foo.prototype.constructor = 3; //a dummy value
var obj2 = new Foo();
console.log(obj2);
console.log(obj2.constructor === Foo);
function Bar(){
this.foo = true;
}
console.log('obj3');
Bar.prototype = 3;
var obj3 = new Bar();
console.log(obj3);
console.log(obj3.constructor === Bar);
console.log(obj3.constructor === Object);