JavaScript Classes - How do you write them

Status
Not open for further replies.

TheJet

Ars Praefectus
4,598
Subscriptor++
So, Clint's post about the IE issues with the site JavaScript prompted a question for me that's been sitting in the back of my mind for quite a while. I've been using the .prototype method for the stuff I've been working on, primarily because that's 'just how it's done' for .NET AJAX client-side behaviors/extenders. A lot of jQuery stuff uses what I call the 'function' method, both seem to have benefits and drawbacks, so I'm wondering which method you use when designing JavaScript classes and why you take that approach:

For those not familiar [and pardon any mistakes here]

prototype method
Code:
    function SampleClass() {
        // constructor details go here...
        this.publicVar = "publicVar: Set in initialize()";
        this._privateVar = "privateVar: Set in initialize()";
    };
        
    SampleClass.prototype = {
        ShowMe: function() {
            alert("This is a public variable: " + this.publicVar);
            alert("This is a private variable: " + this._privateVar);
        },

        UpdatePrivateVar: function(newValue) {
            this._privateVar = newValue;
        }
    };

    var myClass = new SampleClass();
    myClass.ShowMe();
    myClass.publicVar = "New Public Value";
    myClass.UpdatePrivateVar("New Private Value");
    myClass.ShowMe();

function method
Code:
    function SampleClass() {
        // constructor details go here...
        this.publicVar = "publicVar: Set in constructor";
        var _privateVar = "privateVar: Set in constructor";

        this.ShowMe = function() {
            alert("This is a public variable: " + this.publicVar);
            alert("This is a private variable: " + _privateVar);
        };

        this.UpdatePrivateVar = function(newValue) {
            _privateVar = newValue;
        }
    }
        
    var myClass = new SampleClass();
    myClass.ShowMe();
    myClass.publicVar = "New Public Value";
    myClass.UpdatePrivateVar("New Private Value");
    myClass.ShowMe();

One advantage that seems to come from the 'function' approach is that private variables can actually stay private, which seems handy, but it also seems like private functions aren't really possible using either method, or maybe I'm just not familiar enough with the function approach...

The prototype approach feels somewhat cleaner from a code standpoint...

Experiences/comments/etc with either approach, do you have other approaches that you've used successfully in the past?
 

drogin

Ars Tribunus Angusticlavius
8,283
Subscriptor++
I write mine something like this:

Code:
var MyClass = function(options) {

    //more or less a static function
    var helper = function(arg1, arg2) {
        return arg1 + arg2;
    };

    //this is returning an actual instance of the class, but we wrap it in a function call to have real "private" members
    return function(){
        
        //locally scoped to the function and therefore private to this instance
        var _private1 = options.anotherThing;

        //this is the real instance, I promise. Lexical closure allows us to access our "private" variables
        return {
            getPrivate1 : function() { return _private1; },
            setPrivate1 : function(value) { _private1 = value; },
            doStuff : function(arg1) { var i = helper(arg1, _private1); return i; }
        };

    }(); //the parens are important because it invokes our anonymous function which returns our instance
};


var instance = new MyClass({ something : 1, somethingElse : 2, anotherThing : 3 });

//we get 9 because we _private1 should be 3 at this point
alert(instance.doStuff(6));
        
//notice how our value changes to 8? That's because we can modify _private1
instance.setPrivate1(2);
alert(instance.doStuff(6));
        
//we still get 8, because event though we defined _private1 on the class, our method are actually referencing the
//locally scoped _private1 via closure!
instance._private1 = 100;
alert(instance.doStuff(6));

As you can see from the above, doing it this way I get "private" members of the instance, as well as "static" members of the class.
 

Magus`

Ars Legatus Legionis
30,136
Subscriptor++
At my last job, I'd started using this: http://dpaste.com/176828/

And then writing classes like this:

Code:
/** Class: Events
 *  A class to provide a basic event structure.
 */
var Events = Class.extend({
	init: function ()
	{
		this._super();
		this._events = {};
	},

	/** Function: addEvent
	 *  Adds an event handler.
	 *
	 *  Parameters
	 *    (String) ev - Which event to add the handler to
	 *    (Function) func - The function to add to the event
	 */
	addEvent: function (ev, func)
	{
		if (!this._events[ev])
		{
			this._events[ev] = [];
		}
		this._events[ev].push(func);
	},

	/** Function: fireEvent
	 *  Fires an event.
	 *
	 *  Parameters
	 *    (String) ev - Which event to fire
	 *    (Array) args - Arguments to pass to each event handler
	 */
	fireEvent: function (ev, args)
	{
		if (!this._events[ev]) { return; }

		for (var i = this._events[ev].length - 1; i >= 0; i--)
		{
			this._events[ev][i].apply(this, args || []);
		}
	}
});
 
drogin++

Delegation is a superset of Inheritance (provably. See Theory of Objects by Cardelli and Abadi), though yes, we aren't really seeing that in the examples above. God the world would have been a better place if Self had beaten Java, or if JavaScript hadn't been such a shitty re-design of self. At least the JS implementations are catching up to what was state of the art 2 decades ago in VMs for highly dynamic languages.

OP: you want to read Javascript: The Good Parts
 
Status
Not open for further replies.