← home← blog

A quick start JavaScript class structure

22 Jul 2012

A google around reveals lots of ways to structure your JavaScript code. My method is nothing special, nothing new and is probably covered hundreds of times across the web.

But, it's always useful to see different methods, right? Maybe you hadn't seen this way yet...

var myClass = function() {

    var privateVar = 'do not look at me from the outside';

    return {

        publicVar: 'access me from anywhere',

        fname: '',

        init: function(fname) {
            this.fname = (fname !== undefined) ? fname : 'guest';
            console.log('you\'ve kicked this class off, ' + this.fname);

        getPrivateVar: function() {
            return privateVar;



myClass.init(); // you've kicked this class off, guest 
myClass.init('ben'); // you've kicked this class off, ben
console.log(myClass.publicVar); // access me from anywhere
console.log(myClass.privateVar); // undefined
console.log(myClass.getPrivateVar()); // do not look at me from the outside

I'm always interested in people's methods of structuring their code, so stick a link to a Gist or a JSFiddle and share your ways in the comments section...

I'm available for hire

Hire me