Skip to content

Instantly share code, notes, and snippets.

@dgowrie
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save dgowrie/24fb3483051579b89512 to your computer and use it in GitHub Desktop.

Select an option

Save dgowrie/24fb3483051579b89512 to your computer and use it in GitHub Desktop.
"Class" like structure for JavaScript - a hybrid of the Module Pattern (a locally scoped object variant) and the Prototype Pattern... similar in result to the 'standard' (if such a thing) "Revealing Prototype Pattern"
// "Class" like module pattern
(function (NS) {
'use strict';
// constructor for the Person "Class", attached to global namespace
var Person = NS.Person = function (name) {
this.name = name;
};
// may not be necessary, but safe
Person.prototype.constructor = Person;
// private method
var _privateMethod = function() {
// do private stuff
// use the "_" convention to mark as private
// this is scoped to the modules' IIFE wrapper, but not bound the returned "Person" object, i.e. it is private
};
// public method
Person.prototype.speak = function() {
console.log("Hello there, I'm " + this.name);
};
return Person;
})(window.NS = window.NS || {});
// use your namespaced Person "Class"
var david = new NS.Person("David");
david.speak();
// and a variant more along the lines of the 'standard' Revealing Prototype Pattern
(function (NS) {
'use strict';
// constructor for the Person "Class", attached to global namespace
var Person = NS.Person = function (name) {
// reset constructor (the prototype is completely overwritten below)
this.constructor = Person;
// set properties unique for each instance
this.name = name;
};
// all methods on the prototype
Person.prototype = (function() {
// private method
var _privateMethod = function() {
// do private stuff
// use the "_" convention to mark as private
// this is scoped to the IIFE but not bound to the returned object, i.e. it is private
};
// public method
var speak = function() {
console.log("Hello there, I'm " + this.name);
};
// returned object with public methods
return {
speak: speak
};
}());
})(window.NS = window.NS || {}); // import global namespace
// use your namespaced Person "Class"
var david = new NS.Person("David");
david.speak();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment