Rocky Singh
Rocky Singh

Reputation: 15440

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.

Upvotes: 5

Views: 77

Answers (2)

Neil Mountford
Neil Mountford

Reputation: 2001

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/

Upvotes: 2

jcubic
jcubic

Reputation: 66650

You can add methods to object dynamicaly:

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

Upvotes: 0

Related Questions