web development

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

Admin

Share
Published by
Admin
Tags: javascript

Recent Posts

Unveiling the Intricacies of the Tinder Algorithm: 5 Surprising Metrics

Monitored by Tinder The inner workings of the Tinder algorithm remain shrouded in secrecy, known…

1 month ago

Is Shopping Temu Safe

Use fav19073 30% OFF Shop Now I recently had a fantastic buying experience on Temu,…

4 months ago

Cheap Netflix Subscription

Unlocking Affordable Streaming: How Gamsgo.com is Revolutionizing Netflix Subscriptions Sign Up Save1 coupon code for…

5 months ago

Domains for SALE.

razerkeyb.com gloriousmouse.com

9 months ago

How to Start your own vegetable garden?

Planting your own vegetables and fruit is a great way to save money and eat…

1 year ago

Jobs AI can’t replace

While AI has the potential to automate many tasks, there are still some jobs that…

1 year ago