Note: You are not inheriting from People
, but you are reusing People
's constructor function.
Suggestion 1:
Make sure that you are not creating global variables.
var People = function (name) { // var at the beginning is important
...
...
var Employee = function (name) { // var at the beginning is important
...
...
var Jonh = new Employee("Jonh Smith");
Suggestion 2:
The constructor function should have a way to initialize other variables as well.
var People = function (name, age) {
this.name = name || null;
this.age = age || null;
};
var Employee = function (name, age, idCode, salary) {
People.call(this, name, age);
this.IdentificationCode = idCode || null;
this.salary = salary || null;
}
As People
doesn't have any methods in its prototype, this should be fine.
But if you have methods in People
's prototype and you want them to be available to your derived objects as well, you can do this
var People = function (name, age) {
this.name = name || null;
this.age = age || null;
};
People.prototype.getData = function() {
return [this.name, this.age];
};
Now define Employee
like this
var Employee = function (name, age, idCode, salary) {
People.call(this, name, age);
this.IdentificationCode = idCode;
this.salary = salary;
}
// Make the Employee's prototype an object of parent class's prototype
Employee.prototype = Object.create(People.prototype);
Then do,
var Jonh = new Employee("Jonh Smith", 25, 35632, 3500);
console.log(Jonh.getData());
Now, it will invoke People
's getData
and will print
[ 'Jonh Smith', 25 ]
Note: This type of inheritance is normally called as Prototypal inheritance.