JavaScript Classes - How do you write them

Status
You're currently viewing only TheJet's posts. Click here to go back to viewing the entire thread.
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?
 
Status
You're currently viewing only TheJet's posts. Click here to go back to viewing the entire thread.
Not open for further replies.