Search code examples
javascriptinheritanceprototypal-inheritance

How to override a javascript IIFE returned method in an object?


I have one IIFE content which looks like this:

var A = (function() { 
     var method1 = function() { 
         alert("PARENT METHOD");
     }
     var method2 = function() {
        method1();
     }

    return {
        method1: method1,
        method2: method2
    }
})();

I want to override this method1 in another javascript object in a way when this method2 executes then it will call the overriden method1, not this original method1. Thanks in advance.


Solution

  • You are going to need to use prototype in order to accomplish this the way you would like. Take a look at the example below.

    var A = (function() { 
    		 var api = function(){}
         
         api.prototype.method1 = function() { 
             console.log("PARENT METHOD");
         }
         
         api.prototype.method2 = function() {
            this.method1();
         }
    
        return new api();
    })();
    
    A.method2();
    A.method1 = function() { console.log('child method');}
    A.method2();