Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Polymorphism in JavaScript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 513
    Comment on it

    Polymorphism is one of the main feature of Object Oriented Programming.Polymorphism in Object-Oriented Programming is the ability to create an object that has more than one form. Polymorphism can be used when there is a hierarchy of classes and they are linked by inheritance.
    JavaScript polymorphism has one feature that is different than other object-oriented languages, as in javascript we can add and override members on the fly, after an object has been created. Also an object can add or lose properties and behaviors over time.


    Lets explain it with an example:

    <script type="text/javascript">
    
      employee = function(name, age) {
        this.name=name;
        this.age=age;
        this.userInfo=function() {
          return "my name is " + this.name + "my age is " +
             + this.age;
        }
      }
    
      manager = function(name, age, salary){
        this.name=name;
        this.age=age;
        this.salary=salary;
        this.userInfo=function() {
          return "my name is " + this.name + "my age is " +
             + this.age + "my salary is " + this.salary;
        }
      }
    
      function getInfo(obj) {
        document.write(obj.getInfo()+"<br>");
      }
    
      var employee = new employee('John',80);
      var manager = new manager('Peter',80,50000);
      getInfo(manager);
      getInfo(employee);
     
    </script>

    So we have seen that in Polymorphism we do not have to know the exact type of the object in advance because the behavior is determined at run-time. This is called late binding or dynamic binding.

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: