Skip to content

Instantly share code, notes, and snippets.

@Kotauror
Last active March 6, 2018 19:34
Show Gist options
  • Save Kotauror/bd612914f4e6e33c4d69aca08af81842 to your computer and use it in GitHub Desktop.
Save Kotauror/bd612914f4e6e33c4d69aca08af81842 to your computer and use it in GitHub Desktop.
Limiting the scope in JS by using module pattern

Limiting the scope in JS by using module pattern

JS, unlike Ruby, doesn't have classes to separate concerns or the concept of private method. In order to limit the scope of of our code, we can use the module pattern that will make some code available while keeping other parts of code hidden.

Code basis

Question.js

"use strict";

(function(exports) {
  var QUESTION_MARK_COUNT = 2;

  function question(string) {
    return string + "?".repeat(QUESTION_MARK_COUNT);
  };

  exports.question = question;
})(this);

Example of use: The question method accepts one argument - a string

question("Justyna"); // Justyna??

Exclaim.js

"use strict";

(function(exports) {
  function exclaim(string) {
    return string + "!";
  };

  exports.exclaim = exclaim;
})(this);

Example of use: The exclaim method accepts one argument - a string

exclaim("Justyna"); // Justyna!

Interrobang.js

"use strict";

(function(exports) {
  function interrobang(exclaim, question, string) {
    return exclaim(question(string));
  };

  exports.interrobang = interrobang;
})(this);

Example of use: The interrobang method accepts three arguments - an exclaim method, a question method and a string

interrobang(exclaim, question, "Justyna"); //Justyna??!

Analysis

The interrobang method is using both exclaim and question method on the same string.

Both these methods are inside of other functions. Interrobang can use them thanks to the fact that they are exported outside the function. See lines:

  exports.question = question;

and

  exports.exclaim = exclaim;

If we would like to use the variable below set in question.js in any other function:

var QUESTION_MARK_COUNT = 2;

it would cause a referrence error (Uncaught ReferenceError: QUESTION_MARK_COUNT is not defined), as this variable is set inside of two functions and hasn't been exported outside.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment