• Snippet: JavaScript
Object-Oriented JavaScript Template
A simple pattern for writing applications in JavaScript based on object–oriented principles.
Coming from more strictly-typed languages, developers new to JavaScript may find its implementation of object-oriented principles, a little wonky. If this is you, the template below is an example of how I like to write and organize my applications. I hope it can help you better understand how to accomplish certain object-oriented tasks in the language.
The Class
By wrapping your class in a self-invoking function you can create "private" variables and functions available to your object and nothing else. Learn more about the modular pattern here.
var Person = (function () {
// local (private) vars
var _greeting = "Hi";
// constructor
var Person = function ( name, age ) {
this.name = name;
this.age = age;
return this;
}
// class methods
Person.prototype.sayHello = function() {
return _greeting + ", I'm " + this.name + " and I am " + age;
};
// static methods
Person.setGreeting = function( greeting ) {
_greeting = greeting;
};
return Person;
})();
You would then create instances and invoke their methods like this.
// creating new instances
var harry = new Person( "Harry Potter", 11 );
var ron = new Person( "Ron Weasley", 11 );
// invoking class attributes and methods
harry.sayHello(); // Hi, I'm Harry Potter and I am 11.
ron.sayHello(); // Hi, I'm Ron Weasley and I am 11.
// invoking static methods
Person.setGreeting( 'Greetings' );
harry.sayHello(); // Greetings, I'm Harry Potter and I am 11.
Extension
Extending the app to add functionality is very easy; create a new module, include your object and then add attributes and methods.
(function ( Person ) {
// local variables
var _newGreeting = "Wazzup?";
// adding a class method
Person.prototype.newGreeting = function(){
return _newGreeting + " I'm " + this.name;
};
// adding a static method
Person.setNewGreeting = function( greeting ){
_newGreeting = greeting;
};
})( Person );
harry.newGreeting(); // Wazzup? I'm Harry Potter
Person.setNewGreeting( "What's your name?" );
Inheritance
Inheritance in javascript can be a little quirky, but this is how I do it.
var Wizard = (function ( Person ) {
// constructor
var Wizard = function ( name, age ) {
// initialize the parent
Person.call( this, name, age );
// put all your new attributes here ...
return this;
}
// inherit parent's class methods
Wizard.prototype = Object.create( Person.prototype );
Wizard.prototype.constructor = Wizard;
// inherit parent's static methods individually
// or use an extend function add them dynamically
Wizard.someStaticMethod = Person.someStaticMethod;
// put all new class and static methods here ...
return Wizard;
})( Person );
var harry = new Wizard( "Harry Potter", 11 );
harry.sayHello(); // Hi, I'm Harry Potter and I am 11.
Learn More
For more, you can find my full JS template here and a jQuery version of the same, here.