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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.