Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
You might think that you can replace the
prototype property entirely at any time and that all
instances will be updated, but this is not correct. When you create an
instance, that instance will be tied to the prototype that was “minted” at the time of
instantiation. Providing a new object as the prototype
property does not update the connection between instances already created
and the new prototype.
But remember, as I stated above, you can update
or add to the originally created prototype object and those values remain
connected to the first instance(s).
<!DOCTYPE html><html lang="en"><body><script>
var Foo = function Foo(){};
Foo.prototype.x = 1;
var FooInstance = new Foo();
console.log(FooInstance.x); // logs 1, as you think it would
// now let's replace/override the prototype object with a new Object() object
Foo.prototype = {x:2};
console.log(FooInstance.x); /* logs 1, WHAT? Shouldn't it log 2, we just updated prototype */
/* FooInstance still references the same state of the prototype object that
was there when it was instantiated. */
// create a new instance of Foo()
var NewFooInstance = new Foo();
// the new instance is now tied to the new prototype object value (i.e., {x:2};)
console.log(NewFooInstance.x); // logs 2
</script></body></html>