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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️