TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

JavaScript OOPs Polymorphism

JavaScript OOPs Polymorphism with javascript tutorial, introduction, javascript oops, application of javascript, loop, variable, data types, operators, javascript if, switch, operators, objects, form validation, map, typedarray etc.

<< Back to JAVASCRIPT

JavaScript Polymorphism

The polymorphism is a core concept of an object-oriented paradigm that provides a way to perform a single action in different forms. It provides an ability to call the same method on different JavaScript objects. As JavaScript is not a type-safe language, we can pass any type of data members with the methods.

JavaScript Polymorphism Example 1

Let's see an example where a child class object invokes the parent class method.

<script>
class A
  {
     display()
    {
      document.writeln("A is invoked");
    }
  }
class B extends A
  {
  }
var b=new B();
b.display();
</script>
Test it Now

Output:

A is invoked

Example 2

Let's see an example where a child and parent class contains the same method. Here, the object of child class invokes both classes method.

<script>
class A
  {
     display()
    {
      document.writeln("A is invoked<br>");
    }
  }
class B extends A
  {
    display()
    {
      document.writeln("B is invoked");
    }
  }

var a=[new A(), new B()]
a.forEach(function(msg)
{
msg.display();
});
</script>
Test it Now

Output:

A is invoked
B is invoked

Example 3

Let's see the same example with prototype-based approach.

<script>
function A()
{
}
A.prototype.display=function()
{
  return "A is invoked";
}
function B()
{
  
}

B.prototype=Object.create(A.prototype);

var a=[new A(), new B()]

a.forEach(function(msg)
{
  document.writeln(msg.display()+"<br>");
});
<script>
Test it Now

Output:

A is invoked
B is invoked
Next TopicJS Abstraction




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf