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.
3.147.44.182