What is polymorphism in javascript?

I read some possible articles that I could find on the Internet about polymorphism. But I think that I could not fully understand the meaning of this and its importance. Most articles do not say why this is important and how I can achieve polymorphic behavior in OOP (of course, in JavaScript).

I cannot provide sample code because I have no idea how to implement it, so my questions are below:

  1. What is it?
  2. Why do we need this?
  3. How does it work?
  4. How can I achieve this polymorphic behavior in JavaScript?

I have this example. But it’s easy to understand what the result of this code will be. This does not give a clear idea of ​​the polymorphism itself.

function Person(age, weight) { this.age = age; this.weight = weight; this.getInfo = function() { return "I am " + this.age + " years old " + "and weighs " + this.weight +" kilo."; } } function Employee(age, weight, salary) { this.salary = salary; this.age = age; this.weight = weight; this.getInfo = function() { return "I am " + this.age + " years old " + "and weighs " + this.weight +" kilo " + "and earns " + this.salary + " dollar."; } } Employee.prototype = new Person(); Employee.prototype.constructor = Employee; // The argument, 'obj', can be of any kind // which method, getInfo(), to be executed depend on the object // that 'obj' refer to. function showInfo(obj) { document.write(obj.getInfo() + "<br>"); } var person = new Person(50,90); var employee = new Employee(43,80,50000); showInfo(person); showInfo(employee); 
+73
javascript polymorphism oop functional-programming parametric-polymorphism
Dec 24 '14 at 21:16
source share
7 answers

Polymorphism is one of the principles of object-oriented programming (OOP). It is the practice of designing objects to share behavior and the ability to override common behaviors with specific ones. Polymorphism takes advantage of inheritance to make this happen.

In OOP, everything is considered modeled as an object. This abstraction can be brought down to nuts and bolts for a car or as wide as just a type of car with years, model and model.

To have a scenario with a polymorphic car, there would be a type of base car, and then there would be subclasses that would inherit from the car and provide their own behavior on top of the basic behaviors that the car could have. For example, the subclass may be TowTruck, which will still have the year of manufacture and model, but may also have some additional behaviors and properties that can be as basic as the IsTowing flag, as complex as the features of the elevator.

Returning to the example of people and employees, all employees are people, but all people are not employees. This means that people will be superclasses, and workers will be a subclass. People may have age and weight, but they do not have a salary. Employees are people, therefore they will have age and weight, but also because they are employees, they will have a salary.

So, to facilitate this, we first write out a superclass (Person)

 function Person(age,weight){ this.age = age; this.weight = weight; } 

And we will provide Man with the opportunity to share his information.

 Person.prototype.getInfo = function(){ return "I am " + this.age + " years old " + "and weighs " + this.weight +" kilo."; }; 

Next we want to have a subclass of Person, Employee

 function Employee(age,weight,salary){ this.age = age; this.weight = weight; this.salary = salary; } Employee.prototype = new Person(); 

And we will redefine the behavior of getInfo, specifying the one that is more suitable for Employee

 Employee.prototype.getInfo = function(){ return "I am " + this.age + " years old " + "and weighs " + this.weight +" kilo " + "and earns " + this.salary + " dollar."; }; 

They can be used similarly to using your source code.

 var person = new Person(50,90); var employee = new Employee(43,80,50000); console.log(person.getInfo()); console.log(employee.getInfo()); 

However, there is not much inheritance here, since the Employee constructor is so much like a human, and the only function in the prototype is overridden. The power in polymorphic design is collaborative behavior.

+84
Dec 24 '14 at 21:48
source share

As explained in this other answer , polymorphism has different interpretations.

The best explanation I have ever read on this is the article by Luke Cardelli , a renowned theorist. The article is called " On Types, Data Abstraction, and Polymorphism . "

What is it?

Cardelli defines several types of polymorphism in this article:

  • universal
    • parametric
    • inclusion
  • Ad hoc
    • oveloading
    • compulsion

It may be a little harder to see the effects of polymorphism in JavaScript, because the more classical types of polymorphism are more obvious in static type systems, while JavaScript has a dynamic type system.

So, for example, there is no method or function overload or automatic casting at compile time in JavaScript. In a dynamic language, we take most of these things for granted. Also, we don’t need something like parametric polymorphism in JavaScript due to the dynamic nature of the language.

However, JavaScript has a type inheritance form that mimics the same ideas of subtype polymorphism (classified as the Cardelli inclusion polymorphism above) similar to what we usually do in other object-oriented programming languages ​​such as Java or C # (as explained in another answer that I shared above).

Another form of polymorphism that is very typical of dynamic languages ​​is called duck typing .

It is a mistake to assume that polymorphism is associated only with object-oriented programming. Other programming models (functional, procedural, logical, etc.) offer various forms of polymorphism in their type systems, probably a little unfamiliar to those that are used only for OOP.

Why do we need this?

Polymorphism contributes to the development of many good attributes in software, among other things, it contributes to modularity and reusability and makes the type system more flexible and flexible. Without this, it would be very difficult to talk about types. Polymorphism ensures that one type can be replaced by other compatible ones, provided that they satisfy a public interface, therefore it also helps to hide information and modularity.

How it works?

It is not so easy to answer, different languages ​​have different ways of its implementation. In the case of JavaScript, as mentioned above, you will see that it materializes in the form of type hierarchies using prototype inheritance, and you can also use it with utility typing.

The topic is a little wide, and you opened two questions in one post. It might be better to start by reading Cardelli's article, and then try to understand polymorphism regardless of the language or programming paradigm, and then you will begin to establish links between theoretical concepts and what any particular language, such as JavaScript, can offer to implement these ideas.

+23
Dec 24 '14 at 22:44
source share

What is the purpose of polymorphism?

Polymorphism makes a system of a static type more flexible, without losing (significant) security of a static type, weakening the conditions of equivalence of types. The proof remains that the program will only work if it does not contain type errors.

A polymorphic function or data type is more general than monomorphic because it can be used in a wider range of scenarios. In this sense, polymorphism is the idea of ​​generalization in strongly typed languages.

How does this apply to javascript?

Javascript has a weak dynamic type system. Such a type system is equivalent to a strict type system containing only one type. We can think of such a type as a huge type of union (pseudo syntax):

 type T = | Undefined | Null | Number | String | Boolean | Symbol | Object | Array | Map | ... 

Each value will be associated with one of these type alternatives at runtime. And since Javascript is weakly typed, each value can change its type any number of times.

If we take a theoretical type point and consider that there is only one type, we can safely say that a Javascript type system does not have the concept of polymorphism. Instead, we have duck typing and implicit type coercion.

But this should not stop us from thinking about types in our programs. Due to the lack of types in Javascript, we need to output them during the coding process. Our mind should stand for the missing compiler, i.e. As soon as we look at the program, we should recognize not only algorithms, but also basic (possibly polymorphic) types. These types will help us create more reliable and more reliable programs.

To do this correctly, I will give you an overview of the most common manifestations of polymorphism.

Parametric polymorphism (aka generics)

Parametric polymorphism suggests that different types are interchangeable, because types do not matter at all. A function that defines one or more parameters of a parametric polymorphic type does not need to know anything about the corresponding arguments, but treat them anyway, because they can take any type. This is quite limiting, since such a function can only work with those properties of its arguments that are not part of their data:

 // parametric polymorphic functions const id = x => x; id(1); // 1 id("foo"); // "foo" const k = x => y => x; const k_ = x => y => y; k(1) ("foo"); // 1 k_(1) ("foo"); // "foo" const append = x => xs => xs.concat([x]); append(3) ([1, 2]); // [1, 2, 3] append("c") (["a", "b"]); // ["a", "b", "c"] 

Ad-hoc polymorphism (aka overloading)

Ad-hoc polymorphism says different types are equivalent only for a specific purpose. To be equivalent in this sense, a type must implement a set of functions specific to this purpose. A function that defines one or more ad-hoc parameters of a polymorphic type must then know which sets of functions are associated with each of its arguments.

Ad-hoc polymorphism makes the function compatible with a larger type domain. The following example illustrates the purpose of map-over and how types can implement this restriction. Instead of a set of functions, the "displayed" restriction includes only one map function:

 // Option type class Option { cata(pattern, option) { return pattern[option.constructor.name](option.x); } map(f, opt) { return this.cata({Some: x => new Some(f(x)), None: () => this}, opt); } }; class Some extends Option { constructor(x) { super(x); this.x = x; } }; class None extends Option { constructor() { super(); } }; // ad-hoc polymorphic function const map = f => t => t.map(f, t); // helper/data const sqr = x => x * x; const xs = [1, 2, 3]; const x = new Some(5); const y = new None(); // application console.log( map(sqr) (xs) // [1, 4, 9] ); console.log( map(sqr) (x) // Some {x: 25} ); console.log( map(sqr) (y) // None {} ); 

Subtype polytype

Since the other answers already cover the subtype polymorphism, I skip it.

Structural polymorphism (aka strutrual subtyping)

Structural polymorphism suggests that different types are equivalent if they contain the same structure in such a way that one type has all the properties of another, but may include additional properties. At the same time, structural polymorphism is duck printing during compilation and certainly offers some additional type safety. But, claiming that two values ​​are of the same type only because they have some properties, he completely ignores the semantic level of values:

 const weight = {value: 90, foo: true}; const speed = {value: 90, foo: false, bar: [1, 2, 3]}; 

Unfortunately, speed is considered a subtype of weight , and as soon as we compare the value properties, we actually compare apples to oranges.

+8
Nov 26 '16 at 9:43
source share

what it is?

Poly = many, morphism = change in form or behavior.

why do we need this?

In programming, it is used when we want the function interface (let the function X) be flexible enough to accept different types or number of parameters. In addition, based on a change in the types of parameters or numbers, we might want the function X to behave differently (morphism).

How it works?

We write several implementations of the function X, where each implementation accepts different types of parameters or the number of parameters. Based on the type or number of parameters, the compiler (at runtime) decides which implementation of X should be executed when X is called from some code.

how can i achieve this polymorphic behavior in javascript?

JS is not a typed language, so it really is not intended to use OOP concepts such as polymorphism. However, the new version of JS now includes classes, and it is likely that polymorphism might also start to make sense in JS. Other answers lead to some workarounds.

+6
Dec 16 '16 at 8:12
source share

JavaScript is an interpreted language, not a compiled language.

Compilation time Polymorphism (or static polymorphism) Compilation time polymorphism is nothing more than method overloading in java, C ++

Thus, method overloading is not possible in javascript.

But Dynamic (run time) polymorphism is a polymorphism that existed at runtime, therefore method overriding is possible in javascript

another example is PHP.

+2
May 4 '17 at 7:44
source share

Polymorphism means that the ability to call the same method for different objects, and each object reacts differently, is called POLYMORPHISM .

  function Animal(sound){ this.sound=sound; this.speak=function(){ return this.sound; } } //one method function showInfo(obj){ console.log(obj.speak()); } //different objects var dog = new Animal("woof"); var cat = new Animal("meow"); var cow = new Animal("humbow"); //responds different ways showInfo(dog); showInfo(cat); showInfo(cow); 
+1
Aug 28 '18 at 11:19
source share

@SooRaj Patil Bhak MC Kya Bhokaal Liha Hai Be

0
Jan 29 '19 at 5:45
source share



All Articles