4 ms·
Rebinding `this` is the key for sharing methods using prototypal inheritance. It allows methods on the prototype object to dynamically dispatch to methods depen
by wakamoleguy 8y ago
Rebinding `this` is the key for sharing methods using prototypal inheritance. It allows methods on the prototype object to dynamically dispatch to methods depending on the child you are calling it on.
- harimau777 8y agoI had always been taught that inheritance is an anti-pattern and my experience has been that it makes code more complicated. However, I don't have a lot of first hand experience with it. What would the argument be for why you would want to use "this" to implement prototypal inheritance?
- weberc2 8y agoHonestly there’s no use for prototypical inheritance. You get simpler code by avoiding it altogether as with standard OOP inheritance. You were taught correctly.
- jhanschoo 8y agoTraditional class-based inheritance is an antipattern compared to composition because the child class's API is tightly coupled to its parent: multiple inheritance of implementations is a mess to reason about, and single inheritance unduly privileges a single parent object that makes refactoring hard when the API of the child or parent has to change. Composition does not face these issues because instead of a parent class, the outside class's API is not beholden to the inside class's API. Similarly, in prototypal inheritance, you get to specifically control API by binding or calling 'this' to any choice of object, or select methods to put in other objects, or even replace a method of an object with another method of the same name at runtime, or declare new fields and methods on objects at runtime. This makes prototypal inheritance very open for extension in a way that class-based inheritance cannot be. The downside to this is that JS does not have language features that sufficiently guarantee that an object is closed for modification: in class-based languages classes are a language feature that give a sort of guarantee about the API of an object, but JS objects have no mechanism as powerful as that, and you will need to roll your own. Hence the eventual development of languages and extensions to JS like TS, Reason, Flow that offer these guarantees that transpile to JS.
- zeroname 8y ago> Similarly, in prototypal inheritance, you get to specifically control API by binding or calling 'this' to any choice of object, or select methods to put in other objects, or even replace a method of an object with another method of the same name at runtime, or declare new fields and methods on objects at runtime. None of this sounds like a good idea to me.
- jhanschoo 8y agoIndeed it isn't, and is very lousy to reason about with... until you avail yourself to the sophisticated type systems more commonly found in ML and Haskell through, say, Flow or TypeScript that gives you good guarantees through static analysis as you write.
- spankalee 8y agosuper fixes that use case though.