<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JavaScript &#8211; Pauls Blog</title>
	<atom:link href="https://sterl.org/tag/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>https://sterl.org</link>
	<description></description>
	<lastBuildDate>Fri, 20 Sep 2019 14:16:55 +0000</lastBuildDate>
	<language>de</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>
	<item>
		<title>AngularJS Cheat Sheet</title>
		<link>https://sterl.org/2017/06/angularjs-cheat-sheet/</link>
					<comments>https://sterl.org/2017/06/angularjs-cheat-sheet/#comments</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Fri, 23 Jun 2017 04:26:07 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Angular scope]]></category>
		<category><![CDATA[AngularJS]]></category>
		<category><![CDATA[Component]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[State]]></category>
		<guid isPermaLink="false">http://sterl.org/?p=196</guid>

					<description><![CDATA[Create vs. Get AngularJS application The module dependency array tells AngularJS to create an app, otherwise to load it: Create myApp var app = angular.module('myApp', []); Get myApp var app = angular.module('myApp'); Binding @ Text binding, expressions are supported using {{ }} = Two-way binding &#38; Method binding &#60; One-way binding (usually for components) ?&#8230;]]></description>
										<content:encoded><![CDATA[
<h3 class="wp-block-heading">Create vs. Get AngularJS application </h3>



<p>The module dependency array tells AngularJS to create an app, otherwise to load it: </p>



<table class="wp-block-table"><tbody><tr><td>Create myApp</td><td><code>var app = angular.module('myApp', []);</code></td></tr><tr><td>Get myApp</td><td><code>var app = angular.module('myApp');</code></td></tr></tbody></table>



<h3 class="wp-block-heading"> Binding</h3>



<ul class="wp-block-list"><li> <code>@</code> Text binding, expressions are supported using <code>{{ }}</code></li><li><code>=</code> Two-way binding</li><li><code>&amp;</code> Method binding</li><li><code>&lt;</code> One-way binding (usually for <a rel="noreferrer noopener" href="https://docs.angularjs.org/guide/component" target="_blank">components</a>)</li><li><code>?</code> for an optional binding e.g. <code>@?</code> for an optional string binding </li></ul>



<h3 class="wp-block-heading">Service, Factory, Provider, Value &amp; Controller</h3>



<p><a rel="noreferrer noopener" href="https://docs.angularjs.org/guide/providers" target="_blank">AngularJS Doc</a></p>



<ul class="wp-block-list"><li>A <code>Service</code> is a singleton instance of a custom object. In can be used to share state or usually to wrap the remote REST API in a reuseable faction. It is injected using the name (<a rel="noreferrer noopener" href="http://cssdeck.com/labs/collab/qhvokdnt" target="_blank">review sample</a>).<br>Basically simple <em>AngularJs</em> beans we want to inject later. </li></ul>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;application/ecmascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;JavaScript&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;js&quot;}">angular.module('myApp').service('myServiceName', ['depedency', function(depedency) {
    var privateState = {foo: 'bar'}; // this will be shared between any we inject this service
    this.publicApi = function(newConfig) {
        return privateState.foo; // shared singleton state
    };
}]);</pre></div>



<ul class="wp-block-list"><li>The <code>Factory</code> follows as the name already tells the factory pattern and so allows us to construct either a complex <code>value</code> we want to inject into our controllers or even already existing JS objects which require any dependencies upfront. Basically wrap beans which need a constructor injection (<a rel="noreferrer noopener" href="http://cssdeck.com/labs/collab/bpvsg28h" target="_blank">review sample</a>). </li></ul>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;application/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;JavaScript&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;js&quot;}">// any bean
function myService($log) {
  this.log = $log;
}
myService.prototype.getState = function() {
  return this.state; // still shared if we like
}
//-- AngularJS starts here
// construct the bean and inject what is needed
angular.module('myApp', []).factory(
    'myServiceFactory', ['$log', function($log) {
  // here is the main difference to service,
  // manually call new
  return new myService($log);
}]);</pre></div>



<h4 class="wp-block-heading">Provider</h4>



<ul class="wp-block-list"><li>A <code>Provider</code> is the base for <code>factory</code> and <code>service</code> and has the biggest flexibility. Most important it can be injected into the config method and so configured before the first usage (<a rel="noreferrer noopener" href="http://cssdeck.com/labs/collab/bslsb0s2" target="_blank">review sample</a>).</li></ul>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;application/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;JavaScript&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;js&quot;}">// my service / or just bean
function myService($log, initValue) {
  this.log = $log;
  this.state = {
    foo: initValue || 'Default state'
  };
  $log.info('Service Constructor called ...');
}
myService.prototype.getState = function() {
  this.log.info('getState called ...');
  return this.state;
}

// create angular myApp
var myApp = angular.module('myApp', []);
// register the provider providing our service
// function name is here only to how that this is the provider
myApp.provider('myService', function myServiceProvider() {
  // config area
  var providerState;
  this.config = function(newState) {
  	providerState = newState;
  };
  // constructor like in factory
  // again the name only indicates that here is where the factory function goes...
  this.$get = ['$log', function myServiceFactory($log) {
  	return new myService($log, providerState);
  }] 
});
// configure the provider / service
myApp.config(['myServiceProvider', function (myServiceProvider) {
	console.info('config:', myServiceProvider);
  myServiceProvider.config('configured state');
}]);
// just use it
myApp.component('c1', {
  controller: ['myService', function(myService) {
    this.state = myService.getState();
  }],
  template: 'C1: &lt;input ng-model=&quot;$ctrl.state.foo&quot;&gt;'
});
myApp.component('c2', {
  controller: ['myService', function(myService) {
    this.state = myService.getState();
  }],
  template: 'C2: &lt;input ng-model=&quot;$ctrl.state.foo&quot;&gt;'
});</pre></div>



<ul class="wp-block-list"><li>A <code>Value</code> is a simple object, int or string we want to make available for injection </li></ul>



<h2 class="wp-block-heading">HTML elements in AngularJS </h2>



<h3 class="wp-block-heading">Access HTML element Directive</h3>



<p> The easiest way is just to use the link method:  </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;application/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;JavaScript&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;js&quot;}">angular.module('myApp).directive('myDirective', function () {
    return {
        restrict: 'A',
        replace : false,
        // scope, the element and the attributes
        link: function ($scope, element, attr) {
            // controller not needed if we have no public API
        }
    }
}</pre></div>



<h3 class="wp-block-heading">Access HTML element in Component </h3>



<p>In a component we can just inject the <code>$element</code>. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;application/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;JavaScript&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;js&quot;}">jsui.component('myComponent', {
        // first we can always inject the element of the component
        controller: ['$element', function ($element) {
            var subEl  = $element.find('.any-class'), // optional search by class
                rawDomEl = subEl[0]; // get the raw DOM element

            });
        }],
        templateUrl: 'app/myTemplate.html'
    });</pre></div>



<h3 class="wp-block-heading">Access raw HTML element </h3>



<p>As you can see in the last example we can access the raw DOM element using <code>[0]</code> on the wrapped element. </p>



<h2 class="wp-block-heading">Restrict in Angular <a rel="noreferrer noopener" href="https://docs.angularjs.org/guide/directive" target="_blank">Directive</a> </h2>



<p>The <code>restrict</code> option is typically set to: </p>



<ul class="wp-block-list"><li><code>'A'</code> &#8211; only matches attribute name</li><li><code>'E'</code> &#8211; only matches element name</li><li><code>'C'</code> &#8211; only matches class name</li><li><code>'M'</code> &#8211; only matches comment </li></ul>



<p> These restrictions can all be combined as needed: </p>



<ul class="wp-block-list"><li><code>'AEC'</code> &#8211; matches either attribute or element or class name </li></ul>



<h2 class="wp-block-heading">URL Routing to AngularJS components</h2>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;application/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;JavaScript&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;js&quot;}">app.config(['$urlRouterProvider', '$stateProvider',
    function($urlRouterProvider, $stateProvider) {
            
        $urlRouterProvider.otherwise('/home');
            .state('home', {
                url: '/home',
                component: 'homeComponent'
            })
    })
    // this could be in an own file
    .component('homeComponent', {
        controller: function () {
            // this.title is available
            console.info(&quot;homeComponent loaded ...&quot;);
        },
        templateUrl: 'home/home.html'
    })
;</pre></div>



<h3 class="wp-block-heading">ocLazyLoad angular components during routing </h3>



<p>As the lifecycle of components is a bit different we have to eager load them using <a rel="noreferrer noopener" href="https://oclazyload.readme.io/" target="_blank">ocLazyLoad</a>: </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;application/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;JavaScript&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;js&quot;}">.state('home', {
    url: '/home',
    component: 'homeComponent',
    resolvePolicy: { deps: { when: &quot;EAGER&quot; } }, // LOAD EAGERLY
    resolve: {
        deps: ['$ocLazyLoad', function ($ocLazyLoad) {
          return $ocLazyLoad.load(
            { // best to store it static somewhere if needed more than once ...
              name: &quot;lazyHome&quot;,
              files: [&quot;home/homeComponent.js&quot;]
            }
          );
        }]
    }
});</pre></div>



<h3 class="wp-block-heading">Access URL parameters </h3>



<p>The easiest way to access the URL params is just to inject <code>$stateParams</code> into the component get read it. A bit cleaner is using the <code>resolve</code> of the <code>state</code> to inject the parameters into the component. As so we have to keep in mind that happens async, which means we have to implement the <code>$onInit</code> method to get hold of the injected values into our component. <a rel="noreferrer noopener" href="https://github.com/angular-ui/ui-router/wiki/URL-Routing#stateparams-service" target="_blank">More to components.</a></p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;application/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;JavaScript&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;js&quot;}">// given this state router we want to pass the vin to our component
.state('app.vehicle', {
    url: '/vehicle/:vin',
    component: 'vehicleComponent',
    // pass the vin from the URL to the component
    resolve: { 
        // could have the same name
        vehicleId: function($stateParams) { return $stateParams.vin; }
   }
})

// component using the VIN, here string binding
app.component('vehicleComponent', {
    bindings: {
        vehicleId: '@'
    },
    // we could access state passing here function($stateParams) 
    // and later with $stateParams.vin, which would couple URL id to components
    // and so we should better inject it ...
    controller: function () { 
        // async called INIT method vinComponent is set
        this.$onInit = function() {
            console.info(this.vehicleId);
        };
        // this is most likely not defined, as the resolve happens async
        console.info(this.vehicleId);
    },
    templateUrl: 'vehicle.html'
});</pre></div>



<h3 class="wp-block-heading">Dynamic ncyBreadcrumb label for AngularJS Components</h3>



<p>Accessing just the <code>$scope</code> doesn&#8217;t always work well during the reload of the page furthermore, it doesn&#8217;t work for components anyhow. The easiest way is just to inject the <code>$breadcrumb</code> service and be done with it: </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;application/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;JavaScript&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;js&quot;}">// state definition
.state('app.customer', {
    url: '/customer/:customerId',
    component: 'customer',
    ncyBreadcrumb: {
        parent: 'app.customers',
        label: '{{ pageLabel || &quot;New Customer&quot; }}'
    }
});

// in the component just assign the label attribute in the ncyBreadcrumb
angular.module('myApp').component('customer', {
    bindings: {
        customerId: '@'
    },
    controller: ['$breadcrumb', function ($breadcrumb) {
        // set the page label
        $breadcrumb.$getLastViewScope().pageLabel = &quot;my page label&quot;;

    }],
    templateUrl: 'customer.html'
});</pre></div>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2017/06/angularjs-cheat-sheet/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>JavaScript Module Pattern or Just Private Variables</title>
		<link>https://sterl.org/2015/07/javascript-module-pattern-or-just-private-variables/</link>
					<comments>https://sterl.org/2015/07/javascript-module-pattern-or-just-private-variables/#respond</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Sat, 11 Jul 2015 14:14:01 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Pattern & Best Practice]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[JS]]></category>
		<category><![CDATA[Module Pattern]]></category>
		<guid isPermaLink="false">http://sterl.org/?p=62</guid>

					<description><![CDATA[JavaScript is a wonderful language to get thinks fundamentally wrong from the start. As so where are many patters around to help us to avoid some of these challenges ;-). The module pattern is one of the most known and used. It helps us to create private variables or better to avoid side effects in&#8230;]]></description>
										<content:encoded><![CDATA[
<p>JavaScript is a wonderful language to get thinks fundamentally wrong from the start. As so where are many patters around to help us to avoid some of these challenges ;-).</p>



<p>The module pattern is one of the most known and used. It helps us to create private variables or better to avoid side effects in a larger JS application between the different JS files we load or frameworks we use.</p>



<h2 class="wp-block-heading">The problem</h2>



<p>Overall the problem is that in JavaScript everything is more or less public. Currently, most frameworks register their name in the Global space, also known as the window Object. You know them as <code>angular</code> or just <code>$</code> or maybe even as <code>Y</code>. </p>



<p>Imagine the following code (<a rel="noreferrer noopener" href="http://output.jsbin.com/muxekusezi/1" target="_blank">jsBin</a>): </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;application/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;JavaScript&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;js&quot;}">// first JS file
var CLASS_NAME = &quot;A1&quot;;
function A1() {}
A1.prototype.sayHallo = function() {
  $('#out').html(CLASS_NAME + &quot;: says hallo!&quot;);
};

// second class in a different JS file
var CLASS_NAME = &quot;B1&quot;;
function B1() {}
B1.prototype.sayHallo = function() {
  $('#out').html(CLASS_NAME + &quot;: says hallo!&quot;);
};

// some code
$('#cmdA1').click(function() {
  new A1().sayHallo();
});
$('#cmdB1').click(function() {
  new B1().sayHallo();
});</pre></div>



<p>It doesn&#8217;t matter which button you press the result will always be <code>B1</code>&nbsp;because we have overwritten the value in <code>CLASS_NAME</code> in the second part.</p>



<p>Even if this sample is somehow of course constructed, this problem can easily happen in a larger JS application. We must take this into account an protect ourself.</p>



<h2 class="wp-block-heading"><strong>The solution</strong></h2>



<p>The solution is pretty straight forward. We just wrap our class definition into an anonymous function. This does not only protect us but it allows us to create really private variables in JS which can&#8217;t be overwritten from outside &#8212; we can protect the access to them with functions.</p>



<p><a href="http://output.jsbin.com/fegexecisu/2" target="_blank" rel="noreferrer noopener">jsBin again</a></p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;application/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;JavaScript&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;js&quot;}">// first JS file
MyGlobal = {};
(function($) {
  var CLASS_NAME = &quot;A1&quot;;
  function A1() {}
  A1.prototype.sayHallo = function() {
    $('#out').html(CLASS_NAME + &quot;: says hallo!&quot;);
  };
  MyGlobal.A1 = A1;
})(window.$); // pass any global scope

// second class in a different JS file
(function($) {
  var CLASS_NAME = &quot;B1&quot;;
  function B1() {}
  B1.prototype.sayHallo = function() {
    $('#out').html(CLASS_NAME + &quot;: says hallo!&quot;);
  };
  MyGlobal.B1 = B1;
})(window.$);

// some code
$('#cmdA1').click(function() {
  new MyGlobal.A1().sayHallo();
});
$('#cmdB1').click(function() {
  new MyGlobal.B1().sayHallo();
});</pre></div>



<h2 class="wp-block-heading"><strong>What have we learned?</strong> </h2>



<ul class="wp-block-list"><li>In JavaScript, the best practice is to wrap our code into anonymous functions</li><li>Define one global scope variable which we use to register all our classes (here MyGlobal)</li><li>Anonymous function also allow us to create private/ protected variables</li></ul>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2015/07/javascript-module-pattern-or-just-private-variables/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
