Does polymorphism apply only to OOP concept in JavaScript? I am trying to use object composition vs prototypal/class inheritance in JavaScript. What would be the implementation of polymorphism in object composition if the concept applies?
Here is an example of prototypal inheritance with the implementation of polymorphism (method overriding , reimplementing render method at the child object)
function HtmlElement() {
this.click = function() {
console.log('clicked');
}
}
HtmlElement.prototype.focus = function(){
console.log('focued');
}
function HtmlSelectElement(items = []) {
this.items = items;
this.addItem = function(item) {
this.items.push(item);
}
this.removeItem = function(item) {
this.items.splice(this.items.indexOf(item), 1);
}
this.render = function() {
return `
<select>${this.items.map(item => `
<option>${item}</option>`).join('')}
</select>`;
}
}
HtmlSelectElement.prototype = new HtmlElement();
HtmlSelectElement.prototype.constructor = HtmlSelectElement;
function HtmlImageElement(src) {
this.src = src;
this.render = function() {
return `<img src="${this.src}" />`
}
}
HtmlImageElement.prototype = new HtmlElement();
HtmlImageElement.prototype.constructor = HtmlImageElement;
const elements = [
new HtmlSelectElement([1, 2, 3]),
new HtmlImageElement('http://')
];
for (let element of elements)
console.log(element.render());
this.foo.bar(), then the specific behaviour obviously varies with whatfoois, which you can influence by passingfooas an argument when composing your object, so that'd be a pretty simple example of polymorphism.