Thursday, July 21, 2011

Calling the base constructor in JavaScript

I thought that in JavaScript while implementing inheritance, it was not possible to call the code in the base constructor like you can do in most object oriented language.

I was wrong. The class Employee constructor, call the constructor of the class Person,
using the call() method. That is how you call any base method that has been overridden.
function Person(lastName, firstName){

    this.LastName   = lastName;
    this.FirstName  = firstName;

    this.getFullName = function(){

        return this.LastName + " " + this.FirstName;
function Employee(firstName, lastName , company){

    // Call the constructor of the base class, firstName, lastName);

    this.Company = company;

    this.getFullName = function(){

        return + 
               " " + this.Company;
Employee.prototype = new Person();

var fred = new Employee("Torres", "Frederic", "ACompany" );


No comments:

Post a Comment