Monday, May 7, 2018

scope - Javascript namespace and private variables

i came across following example in my training guide for HTML5/javascript/css



I don't understand why the private variables from the method are added as private variables in underlying object/namespace ns.



(function () {
this.myApp = this.myApp || {};
var ns = this.myApp;
var vehicleCount = 5;
var vehicles = new Array();
ns.Car = function () { }
ns.Truck = function () { }
var repair = {
description: 'changed spark plugs',
cost: 100
};
}());


this is the explanation the book gives:



An IIFE (pronounced iffy) is an anonymous function expression that has a set of parentheses at the end of it, which indicates that you want to execute the function. The anonymous
function expression is wrapped in parentheses to tell the JavaScript interpreter that the function isn’t only being defined; it’s also being executed when the file is loaded.
In this IIFE, the first line creates the myApp namespace if it doesn’t already exist, which
represents the singleton object that is used as the namespace. Next, an ns variable (for namespace) is created as an alias to the namespace to save typing within the IIFE, so ns can
be used in place of this.myApp. After that, the private members of the namespace are defined
by using the var keyword. Car and Truck are public, so they are prefixed with ns.



I would expect following code if they wanted to make these properties privates of the myApp 'namespace'



(function () {
this.myApp = this.myApp ||
{
var ns = this.myApp;
var vehicleCount = 5;
var vehicles = new Array();
var repair = {
description: 'changed spark plugs',
cost: 100
};
};
ns.Car = function () { }
ns.Truck = function () { }
}());

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...