Out of the box, you can't do it that easily with good x-browser support.
However, jQuery does give you a means to have objects extend eachother: http://api.jquery.com/jQuery.extend/
So you would do:
var extended = $.extend({}, BI, {
init: function () {
console.log('I am init');
}
});
The first argument (empty object, {}
) means that the properties of BI
(the second argument) and the object you pass in will be combined in to the new object.
I wrote a small polymorphic extension to $.extend
for this purpose which will allow you to extend from multiple objects, with the latter item taking precidence:
mergeObjects = function () {
// Convert the arguments Array-like object to an actual array
var args = Array.prototype.slice.call(arguments);
// Only one item? If we give this to $.extend it'll extend jQuery, which is
// not the desired result, so let's spit it back verbatim
if (args.length === 1) {
return args[0];
}
// We need to make sure we're always combining objects starting with a
// completely empty one
args.unshift(true, {});
return jQuery.extend.apply(jQuery, args);
};
So, you can define your base module with common properties like so:
var MyBaseModule.prototype = {
options: {},
getOptions: function () {
return this.options || {};
},
setOptions: function (options) {
this.options = options;
},
log: function () {
// do your logging stuff here
},
error: function () {
// do your error handling stuff here
}
};
And your actual modules:
var MyModule = function () {
// constructor code here
};
var MyModule.prototype = mergeObjects(MyBaseModule, {
// define your module's methods here
});
...now MyModule has "inherited" the options
property and options getter and setter. You can instantiate the new module with new MyModule
;
If you want a vanilla way of doing it, this post may be useful