DEV Community

Cover image for The Mediator Pattern in JavaScript

The Mediator Pattern in JavaScript

jsmanifest on October 30, 2019

Find me on medium Join my newsletter In JavaScript, a widely used and powerful pattern is the Module Pattern. It can be incredibly simple to imple...
Collapse
 
abhinav1217 profile image
Abhinav Kulshreshtha • Edited

Can you elaborate as if I am five?

This isn't how we create public and private code inside though,
 we do it by what's being returned using closure. 
We returned an object which is exposed to the caller.
Collapse
 
remco profile image
Remco

I was about to write an elaborate explanation, but Douglas Crockford already wrote an extensive article about this 😄:

crockford.com/javascript/private.html

The keyword is "closure", an example is visible in a constructor-function:

function Person(firstName, lastName) {
  function fullName() {
    return `${firstName} ${lastName}`;
  }

  this.introduce = function() {
    console.log(fullName());
  }
}

When a Person is created we can call introduce on it, but not fullName, essentially making fullName private.

Keep in mind, closures are not limited to constructors! A closure is defined as "a function with its variable scope". Simplified that means that a function 'remembers' the scope it was defined in.

I hope it helps!

For more info you can check developer.mozilla.org/en-US/docs/W...

Collapse
 
oaphi profile image
Oleg Valter

There is probably a mistake in the title - the pattern described is a revealing module pattern, not the mediator, which essentially is an extension of the observable pattern (in a sense Mediator acts as both an observable [publishing to subscribers] and an observer [receiving messages from subscribers] )

Collapse
 
ankitasinghal profile image
Ankita Singhal

Are the Mediator pattern and module pattern the same ?