Using jQuery, this is the format of most of the classes I write in JS:
$.Tabs = function(options){
var self = this;
this.defaults = {};
var cfg = $.extend(true, {}, this.defaults, options);
this.$elem = cfg.$elem;
function _init(){
var dontInit = false;
if (!cfg.$elem || !cfg.requiredProperty){
alert('missing params');
dontInit = true;
}
if (!dontInit){
self.$elem.bridge(self);
}
}
this.show = function(){};
this.hide = function(){};
_init();
}
The code above is just an example by the way.
My question is, how do you extrapolate common tasks/functionality from your classes, so every new class you write, you don’t have to retype everything again?
I created a Class creation script based off of John Resig’s Simple Javascript Inheritance pattern, which allows you to require certain parameters, bind event listeners for a pub/sub pattern, automatically combine defaults with options passed in, and it creates a bridge between the DOM element and the class instance (i.e $(‘elem’).data(‘instanceNamespace’, classInstance);)
But I’m uncomfortable with continuously using this class script to write my classes because it makes them less portable. But yet, I don’t want all my classes to have so many similarities between them when it feels like those aspects can be abstracted.
Thoughts? Or how do you format your Javascript classes?
Thanks in advance.
Edit: Also, would anyone know the impact using a class creation script has on performance? I’m assuming the extra closures adds overhead but is it enough to make it not worthwhile to use?
I think the idea you are looking for is called a Mix-in.
Note: what follows is just vanilla javascript, no jQuery, but I think you’ll see that prototype inheritance is very well suited to the idea of mixins.
Let’s say you define a simple constructor:
Then we can mixin new abilities by copying the properties over to the new object with the function below:
We can create some useful abilities that we may want to re-use for lots of different classes, so instead of having them all inherit from a common class, we can just mixin the new abilities at runtime:
Note that this is adding the new abilities to only a single object. If we wanted to add these abilities to all
Personobjects, we would need to modify the Person prototype.Now let’s say we have another trivial constructor for Animals:
And let’s say we want all of our animals to have the ability to dance. So we can add the
DanceMixinto theAnimalprototype using a function such as:Now we can make some animals that can all dance…
By the way, I highly recommend you check out the MooTools approach to the problem, which is quite elegant. Here is an example of using
Implementsin MooTools classes to facilitate mixins.