I have the following module with two methods, A()
and B()
:
var Module = (function() {
function A(){
console.log("Module: A");
B();
};
function B(){
console.log("Module: B");
Module.Utils.C(); /* Here is the problem */
};
return {
A:A,
B:B
}
} ());
Say I want to add a new method C()
...
function C(){
console.log("C");
};
...to the above module without touching it, i.e., I don't want to change the existing code of Module
but to extend it to have new C
property.
You will need to do the following after the module definition:
Module.Utils = Module.Utils || {};
Module.Utils.C = function(){
console.log("C");
};
The first line checks whether Module.Utils is defined already and defines it if it isn't. The next part then assigns the function C.
If you try to just do Module.Utils.C = function(){ console.log("C"); };
then you would get an error about Module.Utils being undefined.
I've created a fiddle here showing it working: http://jsfiddle.net/u5R4E/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With