javascript Closure IIFE Immediately Invoked Function

Javascript Closure

This is an example of how to use iffe closure example to avoid collisions with other global variables in your programs. By placing the variable in the function it makes it private and not accessible everywhere else that would create a problem.

// global variable bad because of collisions
// break other programs avoid globals
var names = ['zero', 'one', 'two', 'three', 'four', 'five'];

var digit_name = function (n) {
	return names[n];
}

console.log(digit_name(3)) // 'three'

// SLOW - because we have to create an variable array every time you try invoking it.
// prevents collision of global variables - names
var digit_name = function (n) {
	var names = ['zero', 'one', 'two', 'three', 'four', 'five'];
	return names[n];
}

console.log(digit_name(3)) // 'three'

// closure iife - immediate invoked function 
// it executes the function has access to the variable names in the iffy
var digit_name = (function () {
	var names = ['zero', 'one', 'two', 'three', 'four', 'five'];
	return function (n) {
		return names[n];
	}
})();

console.log(digit_name(3)) // 'three'

 

The third way to do this is the best. To avoid collisions.

Power Constructors

  1. Make an object
    • Object Lateral
    • new
    • Object.create
    • call another power constructor
  2. Define some some variables and functions
    • These become private members
  3. Augment the object with privileged methods.
  4. Return the object
function myPowerConstructor(x) {
	var that = otherMaker(x);
	var secret = f(x);
	that.priv = function () {
		//secret x that
	};
	return that;
}

 

Functional Inheritance

function gizmo(id) {
	return {
		id: id,
		toString: function () {
			return "gizmo " + this.id;
		}
	};
}

function hoozit(id) {
	var that = gizmo(id);
	that.test = function (testid) {
		return testid === this.id;
	};
	return that;
}

Source:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
https://en.wikipedia.org/wiki/Immediately-invoked_function_expression