In ECMAScript 5, the factory pattern for construction and inheritance is defined as Object.create(). By passing in an object to inherit from, a new object is returned with all connections properly set up.
Let's look at this code snippet:
var x = {
text: "Bonjour",
speak: function(){ alert(this.text); }
};
var y = Object.create(x);
Is my understanding correctly summarized below?
When y is created, it inherits a property called text from its prototype. This means that the property doesn't exist directly on the instance (y.text), but is actually stored on the prototype (y.prototype.text). If we try to access the value of y.text at this point, JavaScript will search for it implicitly, find it on the prototype, and return it.
y.speak(); // alerts Bonjour
However, if I assign a new value to y.text, it does not affect the inherited y.prototype.text. Instead, it creates a new instance property y.text which takes precedence over the inherited y.prototype.text when accessed in the future. Why is this so?
y.text = "Monde";
x.speak(); // still alerts Bonjour >> Why hasn't this changed?
y.speak(); // now alerts Monde