Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a new method to existing modular pattern object

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.

like image 880
Rocky Singh Avatar asked Nov 04 '22 02:11

Rocky Singh


1 Answers

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/

like image 152
Neil Mountford Avatar answered Nov 09 '22 04:11

Neil Mountford