What is functional polymorphism within Javascript? Well, in Object-oriented programming, polymorphism describes how a language is able to process inputs differently depending on their data type (str, arrays, etc). It also outlines the ability to redefine preexisting methods for derived classes. Consider the image below:
The draw() method is attached to the class 'shape'. Polymorphism allows us to derive the draw() method from the shape class and apply it to subclasses (or different data types), in this case: triangles, rectangles and circles because they are all shapes.
In JavaScript, we can use functional polymorphism to delegate functions onto data of different types. For example, arguments is not a real array and, therefore, doesn't have access to the .sort() method on the Array class. However, we can manipulate the code to get the function of sort() onto arguments, despite it not being an Array by doing something similar to the following:
Polymorphism is an important and cool tool in JS that allows us to stay DRY (method delegation) and KISS (borrowing predictable methods from other class types).
References
Programming JavaScript Applications (O'Reilly)
http://raganwald.com/2014/04/10/mixins-forwarding-delegation.html
No comments:
Post a Comment