A quick start JavaScript class structure

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...

The book The First CTO: The Job Nobody Explains A playbook for the loneliest job in startups. 15 chapters of painful lessons, hard-won advice, and practical frameworks from 5 years as CTO at two seed-stage startups. See the book

Need a collaborator?

Stuck on one technical decision?

A fixed-scope Decision Review is £950: a written recommendation within five working days.

All writing