For the More Curious: Private Module Data

Inside a module, your constructors and prototype methods have access to any variables declared inside the IIFE. As an alternative to adding properties to the prototype, this is a way to share data between instances but make it hidden from any code outside the module. It looks like this:

(function (window) {
  'use strict';
  var App = window.App || {};
  var launchCount = 0;

  function Spaceship() {
    // Initialization code goes here
  }

  Spaceship.prototype.blastoff = function () {
    // Closure scope allows access to the launchCount variable
    launchCount++;
    console.log('Spaceship launched!')
  }

  Spaceship.prototype.reportLaunchCount = function () {
    console.log('Total number of launches: ' + launchCount);
  }

  App.Spaceship = Spaceship
  window.App = App;
})(window);

Other languages provide a way to declare a variable as private, but JavaScript does not. You can take advantage of closure scope (a function using variables declared in the outer scope) to simulate private variables.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.183.210