Skip to content

Instantly share code, notes, and snippets.

@xdmorgan
Last active December 15, 2015 02:29
Show Gist options
  • Save xdmorgan/5187288 to your computer and use it in GitHub Desktop.
Save xdmorgan/5187288 to your computer and use it in GitHub Desktop.
Ultra simple JavaScript class template (there's many ways to shoehorn OOP principles into JS but this is the way I like to do my classes, if you have a preferred method let me know). Follow the simple instructions at the top of the document to instantiate it and view the private/public variables/functions at work.
/* =========================================================
————————————— JS STYLE CLASS TEMPLATE —————————————
============================================================
Link to script in the <head> (or just before the </body>) of
your HTML document, then in the browser's console copy/paste
the following code to instantiate the class:
c = new Class();
Notice fields marked as public are returned upon
instantiation and those marked private are not viewable
from the outside.
- @xDanMorgan (github: dannydev)
========================================================= */
var Class = function(opts){
// class_def = this, for when 'this' is commandeered
var class_def = this;
// PUBLIC STATIC CONSTANTS
this.HELLO_WORLD = 'Hello World!';
// PUBLIC VARS
this.some_var = 'some public value';
// PRIVATE VARS
var some_var = 'some private value';
// CONSTRUCTOR
var init = function(){
class_def.greet();
};
// PUBLIC METHODS
this.greet = function(){
console.log(class_def.HELLO_WORLD);
};
// PRIVATE FUNCTIONS
// PRIVATE UTILS
// CALL CONSTRUCTOR
init();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment