Wednesday, June 22, 2011

Javascript - Child Class that Inherits from a Parent Class

Edit: For a far better and namespaced approach to what I am trying to accomplish here, please refer to Jaco Pretorius' Better JavaScript - User Defined Objects. He has based his methods off of Elijah Manor's extremely useful article covering best practices for JavaScript. I especially like how Elijah is able to expose common bad JS habits for why they can be harmful.


Defining classes this way (as a function returning an object literal) means they will always be public, including each of their members and methods.

// Person class
function Person(curFirstName /* string */, curLastName /* string */) {
    return {
        FirstName: curFirstName,
        LastName: curLastName,
        FullName: function() {
            return( this.FirstName + " " + this.LastName );
        }
    };
}

// Musician class inherits Person class
function Musician(curInstrument /* string */, curPerson /* object */) {
    return {
        Parent: curPerson,
        Instrument: curInstrument,
        Details: function() {
            return( this.Parent.FullName() + " plays a " + this.Instrument);
        }
    };  
}


var musician = new Musician('Gibson ES-355', new Person('B.B.', 'King'));

alert(musician.Details());


// You can add on new public members or methods
musician.InstrumentName = 'Lucille';
musician.MoreDetails = function() { return(this.Details() + ' named, ' + this.InstrumentName); };

alert(musician.MoreDetails());
   Run and execute the above code with JSFiddle


On B.B. King's beloved guitar named, Lucille:
In the winter of 1949, King played at a dance hall in Twist, Arkansas. In order to heat the hall, a barrel half-filled with kerosene was lit, a fairly common practice at the time. During a performance, two men began to fight, knocking over the burning barrel and sending burning fuel across the floor. The hall burst into flames, which triggered an evacuation. Once outside, King realized that he had left his guitar inside the burning building. He entered the blaze to retrieve his beloved $30 guitar, a Gibson semi-hollow electric. Two people died in the fire. The next day, King learned that the two men were fighting over a woman named Lucille. King named that first guitar Lucille, as well as every one he owned since that near-fatal experience, as a reminder never again to do something as stupid as run into a burning building or fight over women. - Wikipedia: B.B. King

No comments:

Post a Comment