I am learning prototype inheritance in Javascript and I tried to write an example which calls a parent method from a child method's prototype. However, I do not get the results which I expected.
Person.js
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greeting = function() {
console.log("Hello, My name is " + this.name + " and I am " + this.age + " years old.")
}
module.exports = Person;
Employee.js
var Person = require('./Person');
var Employee = function(name, age, salary) {
Person.call(this, name, age);
this.salary = salary;
}
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.greeting = function() {
Person.prototype.greeting.call(this);
console.log("My salary is " + this.salary)
}
module.exports = Employee;
Test.js
var Person = require('./Person');
var Employee = require('./Employee');
var p = new Person("Rob", 24);
p.greeting();
var e = new Employee("Jim", 25, 1200000);
e.greeting();
So basically what I have is an Person class which has name and age and a greeting method attached to its prototype which print some data. The Employee class extends Person and has an additional attribute salary. It also overrides the greeting method by printing the salary. However, before printing the salary, it calls the super class' greeting method and then prints the salary.
My expected output was :
Hello, My name is Rob and I am 24 years old.
Hello, My name is Jim and I am 25 years old.
My salary is 1200000
But Actual Output was:
Hello, My name is Rob and I am 24 years old.
Hello, My name is Person and I am 25 years old.
My salary is 1200000
I know that the call() method needs to be passed arguments along with the context this. And it is the name of this (Person) that is being replaced as the name which tells that the classes are not purely inherited since I am calling the method inside. I should be able to use super.methodName() inside but super does not work here.
Please tell me if what I have done is how Inheritance in JS is achieved or if I'm doing something wrong.
PS: I tried to use a super call to greeting like in Java but it gave me an error. Does that mean the Employee class has not extended the Person class ?
this.nameinPerson, it conflicts withFunction.nameproperty.