Question

I am learning JavaScript and am little confused on how to create new JavaScript class based on an existing class and extend it.

I have a Person class which, I have created 2 instances from (John and Suzie). Now, I want to create another classe (Employee) based on Person with few more properties like Employee Number (and is it possibleto go back to John so that he inherits from Employee class).

This is what I have got:

var Person = function (name, age){
    this.name = name || "UNKNOWN";
    this.age= age || "UNKNOWN";
}
Person.prototype.sayHello = function() {
    console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old");
};
var john = new Person("John Smith",72);
var Suzie = new Person("Suzie Brown", 25);
Was it helpful?

Solution

Assign your prototype to an instance of your parent and make sure to call the parent constructor in the child constructor:

var Person = function (name, age){
    this.name = name || "UNKNOWN";
    this.age= age || "UNKNOWN";
}

Person.prototype.sayHello = function() {
    console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old");
};

var Employee = function(name, age, id) {
    Person.call(this, name, age);

    this.id = id || 'UNKNOWN';
};

Employee.prototype = new Person();

Employee.prototype.getHired = function() {
    console.log('ZOMG I GOT HIRED! My ID # is:', this.id);
};

Some examples of using it:

var bob = new Person('Bobby', 25);
console.log(bob.name); //Bobby
console.log(bob.age); //25
console.log(bob.id); //undefined
bob.sayHello(); //Hello, my name is Bobby and I am 25 years old

var suse = new Employee('Susan', 32, 1337);
console.log(suse.name); //Susan
console.log(suse.age); //32
console.log(suse.id); //1337
suse.sayHello(); //Hello, my name is Susan and I am 32 years old
suse.getHired(); //ZOMG I GOT HIRED! My ID # is: 1337

OTHER TIPS

//create Employee
var Employee = function(name, age, ...extra parameters){
    this.name = name || "UNKNOWN";
    this.age= age || "UNKNOWN";
    //employee related stuff...
};
//extend Person
Employee.prototype = new Person();
var Employee = function (name, age, employeeNumber) {
    ...
};

Employee.prototype = new Person();  // copies Person's name and age to Employee
Employee.prototype.employeeNumber = 0;  // or whatever defaults you want

var Bob = new Employee(...);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top