Christopher
Stoll

Custom JavaScript Object Example

I was talking about JavaScript objects with someone at work today and I wanted a simple example to look at, but I couldn't find one quickly. So, I decided to write up a quick example and post it here for future reference. I'm also posting some links to helpful information on the web.

/*!
 * Example JavaScript Custom Object
 *
 * Copyright 2010, Christopher Stoll
 */

// my custom JavaScript object constructor
function myObject(inParam) {
    // I use underscore for pseudo private vars
    this._objParam = inParam || "no param";
}
    // a method for my object
    myObject.prototype.getParam() = function() {
        var tempParam;
        tempParam = "You gave me " + this._objParam;
        return tempParam;
    }

And, here is an example instantiation:

var myInstance = new myObject(),
    myOtherInstance = new myObject("a param");
alert(myInstance.getParam());
alert(myOtherInstance.getParam());

For more information on JavaScript I frequently turn to the JavaScript Guide at the Mozilla Developer Center, their re-introduction to JavaScript is also a great reference.
Published: 2010-03-24
BloggerJavaScriptCode