In JavaScript or other object-oriented programming languages, polymorphism is achieved by creating different types.
For instance:
class Field {...}
class DropdownField extends Field {
getValue() {
//implementation ....
}
}
Imagine a library forms.js with the following methods:
class Forms {
getFieldsValues() {
let values = [];
for (let f of this.fields) {
values.push(f.getValue());
}
return values;
}
}
This function retrieves all field values, regardless of the field type.
This allows developer A to create the library while developer B can introduce new fields, such as AutocompleterField, without having to modify the library code (Forms.js).
If using functional programming in JavaScript, how could one achieve equivalent functionality?
In case an object doesn't have predefined methods, one may resort to using conditional statements like so:
if (field.type == 'DropdownField')...
else if (field.type == 'Autocompleter')..
However, adding a new type would require modifying the library code.
Is there a more elegant solution in JavaScript that does not rely on object-oriented programming?
While JavaScript is not strictly OOP or FP, are there alternative approaches to tackle this challenge?
Thank you.