0

I have a two functions one is Person and another Employee. Person is parent class and employee should be inherited class. Employee should inherit age and name from Person and should have employerName as its own property.

Person // age, name
Employee //age, name, employerName

I have written the function Person as:

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

How to write the employee function: I tried like this:

function Employee(employerName ){    
  this.employerName = employerName ;    
}

Employee.prototype = new Person(10,'Jack');
var p1 = new Person(10, 'Jack');

How to write the employee function so as to create the instances like this(how to pass the reference of Person object):

e1 = new Employee(25, 'John', 'eBay');
e2 = new Employee(26, 'John-1', 'XYZ');
XXDebugger
  • 1,581
  • 3
  • 26
  • 48

1 Answers1

0

I would suggest you to use classes available with ES6.

According to the MDN docs:

JavaScript classes introduced in ECMAScript 2015 are syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance.

class Person { 
  constructor(age, name) {
    this.age = age;
    this.name = name;
  }
}

class Employee extends Person {
  constructor(age, name, employerName) {
    super(age, name);
    this.employerName = employerName;
  }
}

let e1 = new Employee(25, 'John', 'eBay'),
    e2 = new Employee(26, 'John-1', 'XYZ');
    
console.log(e1);
console.log(e2);

More information about classes.

kunerd
  • 1,076
  • 10
  • 25
kind user
  • 40,029
  • 7
  • 67
  • 77