In the fourth chapter of this & OBJECT PROTOTYPES, Kyle Simpson suggests there are two types of mixins (hacks to mix one object with another) to fake a "child" inheriting from a "parent" in JavaScript:
- Explicit Mixins take shape when two objects are handed into a function which loops through all of the properties of the "parent" by key and assigns all of those properties to the "child" save for those for which a key with the same name already exists at the "child" allowing a "child" property to overpower the "parent" property as would be the reality in real inheritance (and by overpower I really just mean that the "child" gets to keep what it had to begin with without the "parent" stepping on it). If foo has a bar method and baz is a "child" of foo which has its own bar method, yet baz wants to call out to foo's bar method either from within its own bar method or perhaps elsewhere (the qux method?) then it may do so like so: foo.bar.call(this); ...and, in such an approach this is scoped to baz and not foo. As much is crucial to avoid wacky behavior. Note that all of the properties the "child" gets are copies and a change, after the mixing, to a "parent" property will not affect the counterpart "child" property (even if it is an "inherited" property) so, yes, this isn't really inheritance in a normal sense. It's all very ghetto yo. An exception to this rule is that a function copied from "parent" to "child" is not really a copy and both methods have pointers to the same function which was never really tied to the "parent" to begin with beyond the "parent" pointing at it. A change to a function in this setting will affect the same gunk at both "parent" and "child" and you could thus use this as a hack to make changes cascade from one to the other.
- Implicit Mixins just have "child" objects independent from "parent" objects save for calls out to them like so: foo.bar.call(this); ...and these allow the "child" to use a "parent" thing while scoping this to the "child" so that if a method incremented a number and returned it, for example, and that's Kyle's example, the count at the "child" and the "parent" would be independent assuming the thing incremented was this.somethingerother or something else hanging off of this.
No comments:
Post a Comment