I've recently been learning about the revealing module pattern, and it seems like a really good way to structure code in many cases. However, I find myself wanting to use it like a class, so I'm trying to modify it to behave in the following ways:
- Instances get created from the module (doesn't just immediately return its own object)
- The module can take arguments and use them like a constructor (I don't see this in many revealing module examples)
- The module can be extended like a class; extending modules inherit its public properties/methods and can share arguments/parameters
I seem to have achieved this by using just a function expression instead of an IIFE, creating an instance of the parent within the extending module, and passing the extending module's arguments into the parent instance. Here is the full working pattern I've come up with:
var Module = function({text = 'no text given'} = {}) {
var private = {};
private.text = text;
private.logText = function() {
console.log(private.text);
};
var public = {};
public.logText = private.logText;
return public;
};
var Extended = function({extraText = 'no extra text given'} = {}) {
var parent = Module(arguments[0]);
// Note: I chose to use an object as a parameter in this snippet,
// but you could also just use regular parameters and pass in
// arguments instead of arguments[0]
var private = {};
private.extraText = extraText;
private.alertText = function() {
alert(private.extraText);
}
var public = {};
public.logText = parent.logText;
public.alertText = private.alertText;
return public;
};
// TEST INSTANCES
var testModule = Module({ text: "I'm in the console." });
testModule.logText(); // "I'm in the console."
var testExt = Extended({ extraText: "I'm in an alert." });
testExt.logText(); // "no text given"
testExt.alertText(); // alerts "I'm in an alert."
var anotherExt = Extended({
text: "I'm in the console.",
extraText: "I'm in an alert."
});
anotherExt.logText(); // "I'm in the console."
anotherExt.alertText(); // alerts "I'm in an alert."
Now it basically behaves as a class like I was wanting - but I'm wondering what limitations/shortcomings there might be that I'm not seeing. Is the revealing module pattern ever used this way?