“Polymorphism is a concept makes use of inheritance and creates objects that share behaviors but have the ability to also override”

Polymorphism to me seems very similar to inheritance but I think that they key difference is that polymorphism doesn’t have a relationship with objects like inheritance does. It inherits them but shares behaviors in order to make new stuff.

// Polymorphism
function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.info = function() {
  var x = {
    'name': this.name,
    'age': this.age
  }
  return x;
}

Person.prototype.sayAge = function() {
  return this.age;
}

var amy = new Person('Amy', 25);
// Object { name: "Amy", age: 25 }
console.log(amy.info());

function Employee(name, age, dept){
  this.name = name;
  this.age = age;
  this.dept = dept;
}

Employee.prototype = new Person();

var john = new Employee('John', 29, 'IT');
// Object { name: "John", age: 29 }
console.log(john.info());

The above code returns John’s name and age. Polymorphic design can then be used to make use of the Person prototype info and overwrite it to suit the Employee info prototype needs. For example we need to know which dept John works in too.

Employee.prototype.info = function() {
  var x = {
    'name': this.name,
    'age': this.age,
    'dept': this.dept
  }
  return x;
}

// Object { name: "John", age: 29, dept: "IT" }
console.log(john.info());

// 29
console.log(john.sayAge());

The prototypal chain will be inspected for the first occurrence of info which will be Employee’s as it is higher in the chain than Person’s. – (StackoverflowTravis J)

Worthy of Note

Worthy of Note is a site aimed at Web Designers & Developers. It offers a wide range of resources to help assist anyone in the web industry.

View