mercredi 28 juin 2017

Self-Executing Anonymous Function

Was reading a blog post from appendTo and came across this pattern:

(function( skillet, $, undefined ) { 
  //Private Property 
  var isHot = true;

  //Public Property
  skillet.ingredient = 'Bacon Strips';

  //Public Method
  skillet.fry = function() {
    var oliveOil;

    addItem( 'tn Butter nt' );
    addItem( oliveOil );
    console.log( 'Frying ' + skillet.ingredient );
  };

  //Private Method
  function addItem( item ) {
    if ( item !== undefined ) {
        console.log( 'Adding ' + $.trim(item) );
    }
  }

}( window.skillet = window.skillet || {}, jQuery ));

This is intuitive for me, but as soon as this pops up:

//Adding a Public Property 
skillet.quantity = "12";

//Adding New Functionality to the Skillet
(function( skillet, $, undefined ) { 
  //Private Property 
  var amountOfGrease = "1 Cup";

  //Public Method
  skillet.toString = function() {
    console.log( skillet.quantity + ' ' +
                 skillet.ingredient + ' & ' +
                 amountOfGrease + ' of Grease' );
    console.log( isHot ? 'Hot' : 'Cold' );
  };
}( window.skillet = window.skillet || {}, jQuery ));

skilet.ingredient skillet.quantity amountofGrease is accessed into the toString but I'm not entirely sure how isHot is accessed. Can anyone explain how when adding new functionalities later, this design still has access to original variables in the IIFE?

Aucun commentaire:

Enregistrer un commentaire