DEV Community

Jyoti Prakash Pradhan
Jyoti Prakash Pradhan

Posted on

Javascript inheritance

function Person(name, email, mobile) {
  this.name = name;
  this.email = email;
  this.mobile = mobile;
}

Person.prototype.getFirstName = function () {
  return this.name.split(' ')[0];
}

Person.prototype.getLastName = function () {
  var nameArr = this.name.split(' ');
  return nameArr[nameArr.length - 1];
}


function Student(name, email, mobile, age) {
  /**
   * This inherits all methods and properties from Person 
   * class and assign to this, similar to super in es6
  */ 
  Person.call(this, name, email, mobile);
  this.age = age;
}
Enter fullscreen mode Exit fullscreen mode

We have achieved inheritance, now Student instance will have access to the Persons method. But there is one problem here.
Student will not have access to the prototype methods.

To do that we have to add the following lines of code.

/**
* Assign `Student` prototype with `Person` prototype
* Now `Student` has `Person` class proto methods
*/
Student.prototype = Object.create(Person.prototype);

/**
* Here setting proper constructor name for Student class
*/
Object.defineProperty(Student.prototype, 'constructor',
 {
    value: Student,
    enumerable: false,
    writable: true,
 });

Student.prototype.getAge = function() {
  return this.age;
}

var student = new Student('Jyoti Prakash', 'myemail@example.com', '89xxxxxxxx', '25');
Enter fullscreen mode Exit fullscreen mode

image

Top comments (0)