Object JavaScript – Inheritance Using Revealing Module Pattern

10063_580983808600819_401360548_nIn my last post, Understanding Prototypes, you learned that you can use prototypes to implement inheritance. In this post, I will agree with Javier Uria and Pedro Teixeira who posts on MetaDuck, who advocates a way to implement inheritance using the revealing module pattern.

In this approach, you expose the methods of the parent object as you do in any revealing module pattern object. Then in the derived object, you include the variables whose methods and properties you want to expose. You can override a method in the derived object, which is shown in the example.

function Parent(name) {
  // Private variables here
  var myName;
    
  // Constructor
  myName = name;

  // Public interface
  return {
    func1: function () {alert("Parent func1. Name: " + myName); },
    func2: function () {alert("Parent func2. Name: " + myName); }
  }
}

function Child(name) {
  // Private variables here
  var myName,
    exportObj;
    
  // Constructor
  // Inherit
  exportObj = Parent(name + "'s father");

  // Override
  exportObj.func2 = function () {
    alert("Child func2. Name: " + name);
  }

  // Export public interface
  return exportObj;
}

Here is the code as a gist:


function Parent(name) {
// Private variables here
var myName;
// Constructor
myName = name;
// Public interface
return {
func1: function () {alert("Parent func1. Name: " + myName); },
func2: function () {alert("Parent func2. Name: " + myName); }
}
}
function Child(name) {
// Private variables here
var myName,
exportObj;
// Constructor
// Inherit
exportObj = Parent(name + "'s father");
// Override
exportObj.func2 = function () {
alert("Child func2. Name: " + name);
}
// Export public interface
return exportObj;
}
var child = Child("John");
child.func1();
child.func2();

The code produces:

Parent func2. Name: John’s father
Child func2. Name: John

Of course, you can add additional methods and properties on the child object.

References

Combining inheritance with the module pattern

The Module Pattern And Inheritance: A Better Way