I am a programmer who has programmed in several languages, both functional and OO oriented. I programmed some Javascript too, but never used (or had to use) polymorphism in it.
Now, as kind of a hobby project, I would like to port some apps that were written in Java and C# that heavily use polymorhpism to Javascript.
But at a first glance I read lots of ‘It’s possible but …’
So is there an alternative to it?
An example of what I would like to write in JS in pseudolang :
abstract class Shape{ { printSurface() } ; }
class Rect : Shape() { printSurface() { print (sideA*sideB}}
class Circle : Shape() { printSurface() { print { pi*r*r }}
TheApp { myshapes.iterate(shape s) {s.printSurface() } }
So a classic polymorphic case : iterating over baseclass.
I would like to achieve this kind of behaviour. I know it is polymorhism, but are there any other ‘patterns’ that I am overlooking that achieve this kind of behaviour or should I study the inheritance possibilities in Javascript?
As said, JavaScript is a dynamic typed language based on prototypal inheritance, so you can’t really use the same approach of typed languages. A JS version of what you wrote, could be:
Then, in your app:
Or, with duck typing:
You cold also have
Shapeas object without any constructor, that it’s more “abstract class” like:Notice that in this case, you can’t use
instanceofanymore, so or you fallback to duck typing or you have to useisPrototypeOf, but is available only in recent browsers:Object.create is not available in browser that doesn’t implement ES5 specs, but you can easily use a polyfill (see the link).