Search code examples
javascriptlibrariesprivatepublic

How to override "private" function in javascript


I'll explain the problem I'm solving with an example.

I usually define my own libraries in js this way:

window.myLib = (function () {
  var public = {}; // for storing public methods and values
  var private = {}; // for storing private methods and values

  // Atributes and methods here

  return public; // return the public part to be used globally
})();

Now I want to execute an overridable method as a callback from a click event. I would do this:

<input type="checkbox" id="mCheck" onchange="myLib.myMethod()">

Then, in the library I declare the callback "myMethod" that calls another public "overridable" method which I want to use globally, "outside of the library":

  //...
  public.overridable = function(param){console.log("Override this!");};

  public.myMethod = function(){
    if(private.condition) // Just to put some logic
     public.overridable(private.value);
  };
  //...

Here comes the problem. If I redefine the "overridable" method like this:

  myLib.overridable = function(p){console.log(p)};

Then the callback of the click events keeps firing the original "public.override" which outputs the "Override this!" message instead of the value of the parameter.

How can I override the public method to redefine the callback outside the library??

Thanks in advance.


Solution

  • The snippets you've given are already the correct way to do this. If you're having problems it's because of some detail in your implementation - for example, if you store public.overridable in some variable and call it that way instead of referencing public.overridable each time.

    I've put together your snippets in a working example below to show that it works exactly as desired.

    window.myLib = (function () {
      var public = {}; // for storing public methods and values
      var private = {}; // for storing private methods and values
    
      // Atributes and methods here
      public.overridable = function(param){console.log("Override this!");};
    
      public.myMethod = function(){
        if(private.condition) // Just to put some logic
         public.overridable(private.value);
      };
    
      private.condition = true;
      private.value = "test";
    
      return public; // return the public part to be used globally
    })();
    
    myLib.overridable = function(p){console.log(p)};
    <input type="checkbox" id="mCheck" onchange="myLib.myMethod()">