JavaScript, we have prototype-based inheritance. That means an object
has a reference to another certain object, its prototype. Whenever a
property of an object is accessed, the prototype chain is searched for
this property. So if the the object does not have this property itself,
its prototype is inspected for this property and so on.
Now, if you have a constructor function, you can create many instances (objects) referring to the same prototype. When you now add a new property to that prototype, all instances will have this property too (due to the prototype chain).
This is often done to dynamically extend instances but it is only one consequence of prototype inheritance, it is not inheritance itself.
+------------+ +-------------+
| Instance | | Prototype |
| __proto__ -+--->| __proto__ -+-->...
| foo | | bar |
+------------+ +-------------+
Instance has both, the foo and bar properties.Now, if you have a constructor function, you can create many instances (objects) referring to the same prototype. When you now add a new property to that prototype, all instances will have this property too (due to the prototype chain).
This is often done to dynamically extend instances but it is only one consequence of prototype inheritance, it is not inheritance itself.
What is the difference between augmentation and inheritance?Inheritance would be to set the prototype of an object to a certain object so that it is in the prototype chain. Augmentation is just copying properties. The object would own that property then:
+------------+
| Instance |
| __proto__ -+--->...
| foo |
| bar |
+------------+
No comments:
Post a Comment