Question:
A seemingly simple question that I've been researching on and off the for past 2 weeks (please go easy as I'm new to all this!):
How does one neatly implement inheritance in JavaScript when using Require.js and the Revealing Module Pattern?
Example:
Here is an example module which is the base class of some type of 'Component
':
define('Component', [], function () {
"use strict";
var _privateVar = 10;
var _doPrivateThings = function () { /* do stuff */ };
var init = function () { /* do stuff */ };
var update = function () { /* do stuff */ };
return {
init : init,
update : update
};
});
Next I want to implement CakeComponent
which should inherit everything from Component
and allow me to edit/add methods and properties:
define('CakeComponent', ['Component'], function (Component) {
"use strict";
// Setup inheritance
var CakeComponent = function() {}
CakeComponent.prototype = new Component();
// Add/edit methods/properties
CakeComponent.prototype.newMethod = function () { /* do stuff */ };
return {
init : CakeComponent.init,
update : CakeComponent.update,
newMethod : CakeComponent.newMethod
};
});
Firstly, I'm not sure if that makes complete sense, but secondly, my CakeComponent feels a bit gross because now I've got this CakeComponent
redundancy everywhere and I've had to 're-reveal' the init
and update
methods.
I would really prefer something like this (I realise this doesn't make sense, it's really just pseudo-code):
define('CakeComponent', ['Component'], function (Component) {
"use strict";
this.extends(Component);
var newMethod = function () { /* do stuff */ };
return {
newMethod : newMethod
};
});
Any tips or suggestions would really be appreciated. Thanks.
Further Details
- Maybe I should always be creating a class object within the
define
wrapper? I've seen people do this but it seemed unnecessary until I came across this problem. - Would the
.call()
method on the function object be useful at all in this context? e.g. usingComponent.call()
- @Bergi please see below:
define([], function () {
"use strict";
var Component = function () {
var _privateVar = 10;
var _doPrivateThings = function () { /* do stuff */ };
this.init = function () { /* do stuff */ };
this.update = function () { /* do stuff */ };
};
return Component;
});