[JavaScript Patterns] Revealing Prototype

The “Revealing Prototype” pattern is the most complete solution to create JavaScript constructor functions using a prototype and a module. If you understand the basic JavaScript programming techniques, it is not hard to understand the pattern. I bet you will love it.


1. Revealing Prototype Pattern – Structure

The ideas behind the pattern are :

  • Constructor functions with instance variables
  • Methods will be attached to the “prototype” object
  • Method definitions are private and only public interface will be exposed


2. Example

(function (myAppObj) {

  // constructor
  myAppObj.Calculator = function (x) {
    // instance variable
    this.xParam = x;

  myAppObj.Calculator.prototype = (function () {
    // private
    let _adder = function (y) {
          return this.xParam + y;
        _doMultiply = function (y) {
          return this.xParam * y;

    return {
      add: _adder,
      multiply: _doMultiply

}(window.MYAPP = window.MYAPP || {}));

Now you can create an object using the “new” operator.

let calculator = new window.MYAPP.Calculator(10);

console.log(calculator.add(20)); // 30
console.log(calculator.multiply(20)); // 200



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s