Menu

Friday, March 15, 2013

Object Oriented JavaScript Using JQuery

Javascript becomes more and more popular these days, and what best way to write reusable code if not writing it the OO style. JS is not your tipical programming language, the classes in js are not actualy classes, but funcions. Every function has a prototype object that contains methods and properties, we can use this object to write javascript classes.
1. Creating a JS Class:
To create a js class you need to create a function and after that you can use the this keyword to access the object's properties and methods.

var MyClass = function(myName) {
this.myName = myName
};
MyClass.prototype.printMyName = function() {
console.log(this.myName);
};
MyClass.prototype.setMyName = function(myName) {
this.myName = myName;
};
var myObject = new MyClass('Peter Parker');
myObject.printMyName(); // $ Peter Parker
myObject.setMyName('Clark Kent');
myObject.printMyName(); // $ Clark Kent
view raw gistfile1.js hosted with ❤ by GitHub
2. Inheritance
Basicaly to inherit a class you need to extend the parent's class prototype object. To do that we can use jQuery.extend() function.
var MyAbilities = function(myName) {
MyClass.call(this, myName);
this.abilities = [];
};
MyAbilities.prototype = $.extend(MyAbilities.prototype, MyClass.prototype);
MyAbilities.prototype.addAbility = function(name) {
this.abilities.push(name);
};
MyAbilities.prototype.printAbilities = function() {
console.log(this.abilities);
};
var myObject = new MyAbilities('Superman');
myObject.addAbility('xray vision');
myObject.addAbility('flying');
myObject.addAbility('super speed');
myObject.printMyName(); // $ Superman
myObject.printAbilities(); // $ ["xray vision", "flying", "super speed"]
view raw gistfile1.js hosted with ❤ by GitHub
To call a parent method in the context of the child class you can use the call function:
var ChildClass = function() {};
ChildClass.prototype = $.extends(ChildClass.prototype, ParentClass.prototype);
ChildClass.prototype = {
method: function(arg) {
ParentClass.prototype.method.call(this, arg);
}
};
view raw gistfile1.js hosted with ❤ by GitHub
3. How to extend the jQuery Class
var TextBox = function() {
this.init('<input type="text" value="" />');
this.constructor = jQuery;
};
TextBox.prototype = $.extend(TextBox.prototype, jQuery.prototype);
// override a jquery method
TextBox.prototype.text = function() {
return this.val();
};
var tb = new TextBox();
console.log(tb); // [<input type=​"text" value>]
tb.val('Superman');
console.log(tb.val()); // Superman
console.log(tb.text()); // Superman
view raw gistfile1.js hosted with ❤ by GitHub
After creating the object in the constructor we have to set the object's constructor to jquery's constructor, because jquery is using it internaly.

No comments:

Post a Comment