Object Oriented

Polymorphism

JavaScript

 

Polymorphism (ES6)

ECMAScript 2015
class Person {
  constructor(name) {
    this.name = name;
  }
  
  getInfo() {
    return 'name: ' + this.name;
  }
}


class Teacher extends Person {
  constructor(name, salary) {
    super(name);
    this.salary = salary;
  }
  
  getInfo() {
    return 'name: ' + this.name + 
      ', salary: ' + this.salary;
  }
}


class Student extends Person {
  constructor(name, gpa) {
    super(name);
    this.gpa = gpa;
  }
  
  getInfo() {
    return 'name: ' + this.name + 
      ', gpa: ' + this.gpa;
  }
}

JavaScript in design is not type-safe, and does not have a concept of interfaces or contracts, but we can create the effects of Polymorphism.

Here, if we have a shuffle of teacher and student objects inside an array, you can iterate through them and call the getInfo regardless of those object types.

var people = [
  new Student('Bob', 'B+'),
  new Teacher('Alice', 80000),
  new Student('Emma', 'A'),
  new Student('Liam', 'B')
];

for (var i=0; i<people.length; i++) {
  var person = people[i];
  console.log(person.getInfo());
}

The sample code above will print info of each person on the screen:

name: Bob, gpa: B+
name: Alice, salary: 80000
name: Emma, gpa: A
name: Liam', gpa: B
 

Polymorphism

ECMAScript 5
// class Person -----
function Person(name) {
  this.name = name;
}

Person.prototype.getInfo = function() {
  return 'name: ' + this.name;
}


// class Teacher -----
function Teacher(name, salary) {
  Person.call(this, name);
  this.salary = salary;
}

Teacher.prototype = Object.create(Person.prototype);

Teacher.prototype.getInfo = function() {
  return 'name: ' + this.name + 
      ', salary: ' + this.salary;
}


// class Student -----
function Student(name, gpa) {
  Person.call(this, name);
  this.gpa = gpa;
}

Student.prototype = Object.create(Person.prototype);

Student.prototype.getInfo = function() {
    return 'name: ' + this.name + 
      ', gpa: ' + this.gpa;
}

This is the ES5 version of the card above, using prototypes and Function Constructor syntax.