-
Notifications
You must be signed in to change notification settings - Fork 0
02 Classes, Inheritance, Functional..
As a JavaScript developer, it is important to understand how JS's native inheritance capabilities work. One of JS's best features is the ability to create and inherit from objects without classes and class inheritance.
JS's combination of delegate prototypes,runtime object extension, and closures allow three distinct kinds of prototypes to be expressed, which provide significant advantages over classical inheritance.
A delegate prototype is an object that serves as a base of another object. When you inherit from a delegate prototype, the new object gets a reference to the prototype. When accessing a property on an object, it goes up the prototype chain until it is found.
Method delegation can preserve memory resources because you only need one copy of each method to be shared by all instances. However, a major drawback to delegation is that it's not very good for storing state. If you store a state as objects or arrays, mutating any member of the object or array will mutate the member for every instance that shares the prototype. In order to preserve instance safety, you need to make a copy of the state for each object.
Concatenative inheritance is the process of copying the properties from one object to another, without retaining a reference between the two objects. Very powerful, but even better when combined with closures.
Cloning is a great way to store default state for object: commonly achieved using Object.assign().
Functional inheritance makes use of a factory function, and then tacks on new properties using concatenative inheritance.
Functions created for the purpose of extending existing objects are commonly referred to as functional mixins. Primary advantage is that they allow you to use the function closure to encapsulate private data (enforce private state).
Privileged methods are any methods defined within the closure's function scope, which gives them access to the private data.
Classical inheritance creates is-a relationships with restrictive taxonomies. But, we usually employ inheritance for has-a, uses-a, or can-do relationships.
Composition is:
- Simpler
- More expressive
- More flexible