Here is the issue presented:
var Employee = new function(name)
// ------------^^^
{
this.name=name;
}
(The same applies to PermanenetEmployee
.)
The unnecessary use of new
is the problem here. It actually invokes the function, whereas you should call it later as done when assigning to employee
.
It's important to note that the way you are setting up inheritance between them is not ideal. To correctly make PermanenetEmployee
"subclass" Employee
, do the following:
PermanenetEmployee.prototype = Object.create(Employee.prototype);
PermanenetEmployee.prototype.constructor = PermanenetEmployee;
Rather than:
var employee = new Employee("rahul");
PermanenetEmployee.prototype = employee;
...and then have PermanenetEmployee
receive name
and pass it to Employee
:
var PermanenetEmployee = function(name, annualsalary) {
Employee.all(this, name); // <====
// ...
};
...or better yet, utilize ES2015 ("ES6") class
(with transpiling if necessary, e.g., Babel).
Below is a corrected setup along with fixing the typo in PermanenetEmployee
:
var Employee = function(name) {
this.name = name;
};
Employee.prototype.getName = function() {
return this.name;
};
var PermanentEmployee = function(name, annualSalary) {
Employee.call(this, name);
this.annualSalary = annualSalary;
};
// Establish subclass
PermanentEmployee.prototype = Object.create(Employee.prototype);
PermanentEmployee.prototype.constructor = PermanentEmployee.prototype;
PermanentEmployee.prototype.getAnnualSalary = function() {
return this.annualSalary;
};
// Implementation
var pe = new PermanentEmployee("Rahul", 5001);
console.log(pe.getName());
console.log(pe.getAnnualSalary());
And using ES2015:
class Employee {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
class PermanentEmployee extends Employee {
constructor(name, annualSalary) {
super(name);
this.annualSalary = annualSalary;
}
getAnnualSalary() {
return this.annualSalary;
}
}
// Implementation
var pe = new PermanentEmployee("Rahul", 5001);
console.log(pe.getName());
console.log(pe.getAnnualSalary());
Again, remember that transpilation may be required to use that syntax in real-world scenarios for now.