Electricmonk

Ferry Boender

Programmer, DevOpper, Open Source enthusiast.

Blog

Object Oriented Javascript

Saturday, March 4th, 2006

I never really gave it much thought, but it turns out that, naturally, Javascript supports Object Oriented programming. It's a bit awkward, but still:

/*****************************************************************
 * Class description
 *****************************************************************/
function MyClass(param1, param2) {
    /*------------------------------------------------------------
     * PROPERTIES
     *-----------------------------------------------------------*/
    this.property1 = false;
    thisObj.eventHappened = false;

    /*------------------------------------------------------------
     * METHODS
     *-----------------------------------------------------------*/

    /**
     * method1
     */
    this.method1 = function(param2) {
        this.property1 = param2;
    }

    /*------------------------------------------------------------
     * CONSTRUCTOR
     *-----------------------------------------------------------*/
    this.property2 = param1
    this.method1(param2)

    var out = "";
    out += "<div id='"+param1+"'>"+param2+"</div>";
    document.write(out);

    this.div1 = document.getElementById(param1);

    /*------------------------------------------------------------
     * EVENTS
     *-----------------------------------------------------------*/

    /* Because 'this' in events is actually the event, we assign a
     * special variable here so we can reference this object from
     * the events.
     */
    var thisObj = this;

    this.div1.onkeyup = function(e) {
        alert("key");
        thisObj.eventHappened = true;
    }
}

var myClassInstance = MyClass('myDiv', 'Hello!');

The text of all posts on this blog, unless specificly mentioned otherwise, are licensed under this license.