OOP programming in JavaScript can be done in many ways. There are a lot of patterns around.
I will show you two, an Implementation of object inheritance and an implementation of object composition.
This does have absolutely nothing to do with jQuery. jQuery should be used for DOM manipulation and event manipulation. You shouldn't make your core objects and constructors based on jQuery objects. In a game jQuery's role is reading keyboard input and optionally rendering your graphics into the DOM (If you're not using the <canvas> for some reason).
Live example
Inheritance
var Constructor = function(name) {
this.name = name
};
Constructor.prototype.mymethod = function() {
alert("my name is : " + this.name);
};
var obj = new Constructor("foo");
obj.mymethod(); // my name is : foo
Here were defining a Constructor function that you can call to create a new object. You refer to the object inside the constructor with this.
You can add (static) methods and variables to the prototype of the Constructor that will be inherited by the object.
function inherits(child, parent) {
var f = new Function;
f.prototype = parent.prototype;
f.prototype.constructor = parent;
child.prototype = new f;
child.prototype.constructor = child;
}
You may use an inherits function which set's the prototype of a constructor function to an instance of a different constructor. This means that all the methods and properties of that parent object are available on the child
var SecondConstructor = function(name) {
this.name = name + "bar";
};
inherits(SecondConstructor, Constructor);
var obj = new SecondConstructor("foo");
obj.mymethod(); // my name is : foobar
This is JavaScripts prototypical inheritance. Basically you set the prototype of a function to a particular object. Then when you use the function to create objects those objects implement the prototype.
Composition
Using the prototype isn't actually neccesary you can also use object composition instead. This method does require a good understanding of the this state which you can read about elsewhere.
I'm going to cheat and delegate some of the tedious helper functions to underscore.js
var Constructor = function(name) {
this.name = name;
this.mymethod = function() {
alert("my name is : " + this.name);
};
};
var SecondConstructor = function(name) {
var constructor = new Constructor(name + "bar");
_.bindAll(constructor);
_.extend(this, {
"mymethod": constructor.mymethod
});
};
var obj = new SecondConstructor("foo");
obj.mymethod();
Here the SecondConstructor creates an instance of Constructor for itself rather then inheriting from it. It then binds the reference of this on all the methods of that constructor object so that we can delegate the call to mymethod to our own constructor object. This only works for methods but that shouldn't be an issue because you really shouldn't have public fields.