2

I apply inheritance in JavaScript in following way:

var employee = function(name) {
  this.name = name;
}
employee.prototype.getName = function() {
  return this.name;
}
var pEmployee = function(salary) {
  this.salary = salary;
}
pEmployee.prototype.getSalary = function() {
  return this.salary;
}

var employee = new employee("mark");
pEmployee.prototype = employee;
var pe = new pEmployee(5000);
console.log(pe.getName());
console.log(pe.getSalary());

but it showing following error in console:

Uncaught TypeError: pe.getSalary is not a function

Could any one tell me what's the reason behind this error?

Ivar
  • 6,138
  • 12
  • 49
  • 61
GonnaHack
  • 57
  • 1
  • 3
  • 12

1 Answers1

6

It's because you've added getSalary to the object pEmployee.prototype refers to, but then completely replaced pEmployee.prototype with a new object. So naturally the new object doesn't have getSalary.

What you've shown isn't the correct way to set up inheritance in ES5 and earlier. Instead, see inline comments:

var Employee = function(name) {
  this.name = name;
};
Employee.prototype.getName = function() {
  return this.name;
};

var PEmployee = function(name, salary) {
  // Note call to superclass
  Employee.call(this, name);
  // Now this level's initialization
  this.salary = salary;
};

// This sets up inheritance between PEmployee.prototype and
// Employee prototype (then fixes up the
// constructor property)
PEmployee.prototype = Object.create(Employee.prototype);
PEmployee.prototype.constructor = PEmployee;

// NOW you add the method
PEmployee.prototype.getSalary = function() {
  return this.salary;
};

// Usage
var employee = new Employee();
var pe = new PEmployee("Mark", 5000);
console.log(pe.getName());
console.log(pe.getSalary());

See my answer here for a more thorough example, and also what it would look like if you used ES2015's class syntax instead.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875