Adding a new method to an existing modular template 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 do not want to modify the existing code Module, but extend it to have a new property C.

+5
source share
2 answers

After defining the module, you will need to do the following:

Module.Utils = Module.Utils || {};
Module.Utils.C = function(){
  console.log("C");
};

The first line checks if Module.Utils is already defined and determines if it is not. The next part then assigns function C.

Module.Utils.C = function(){ console.log("C"); };, "Module.Utils" undefined.

, , : http://jsfiddle.net/u5R4E/

+2

:

Module.Utils.C = function(){
  console.log("C");
};
0

All Articles