Object Oriented Javascript
// FROM: http://snippetrepo.com/snippets/object-oriented-javascript
// Here I define global variables, which I update in this file
var windowWidth;
// Create a class
var App = function() {
// app variable will reference the App class (like using $this-> in php)
var app = this;
var debug = true; // Allows me to disable things in production, like app.log()
this.init = function() {
// Here is where I call methods when the class is initiated
// I can also pass in variables (sort of like a construct in PHP)
// Example of updating a global variable and calling a method from
// within the class - note "this.methodName = function()" is a public
// method and "var methodName = function()" is a private method
windowWidth = app.getWindowWidth();
};
// Safe way of debugging (console.logs() can break older versions of IE
this.log = function(data) {
if(window.console && debug) {
console.log(data);
}
};
// Example of a simple method
this.getWindowWidth = function() {
return $(window).width();
};
// Example of a method with arguments
this.animateImage = function(selector, positionX, duration) {
selector.animate({'margin-left': '+='+ positionX +'px'}, duration);
};
// Example of a private method
var whatIsPI = function() {
return Math.PI;
};
};
// Instantiate the App class
var app = new App();
// Call the init method
app.init();
// Call public methods with arguments
app.animateImage($('.animated-image'), 450, 1500);
// This is out safe way to console.log()
app.log('This is shown is the console');
// This will fail as we are trying to call a private method
app.log(app.whatIsPI());