Javascript Private Shared Variables

 

 

Apunto este trozo de código pues contiene un concepto interesante que puede ayudar cuando trabajas con Javascript.

Esta técnica permite definir una variable, cuyo ámbito se limita a una función, pero cuyo valor se comparte entre distintas llamadas.

Se parece a las variables privadas estáticas que existían en Visual Basic 6. La idea es la misma.

   1:  function MyFunction() {
   2:      if (!MyFunction.Value1) { // Set the default Value
   3:          MyFunction.Value1 = "Default Value";
   4:      }
   5:      else {
   6:          // The value has been already set   
   7:          MyFunction.Value1 = "Modified Value";
   8:      }
   9:   
  10:      return MyFunction.Value1;
  11:  }
  12:   
  13:  alert("1:" + MyFunction());
  14:  alert("2:" + MyFunction());
  15:   
  16:  // The value is not accesible from outside
  17:  MyFunction.Value1 = "Outside modification";
  18:   
  19:  alert("3:" + MyFunction());

Pruébalo en JS Fiddle: http://jsfiddle.net/69bdw/

 

Básicamente, lo que hacemos es tratar a MyFunction como si fuera un objeto, y asignarle una propiedad.

El valor Value1 existe dentro del contexto de MyFunction, y sólo es modificable desde dentro de él. Además su valor persiste entre llamadas.

Una aplicación interesante de este concepto podría ser una función, que atendiese un evento que se dispara repetidamente, pero para el que sólo realizaremos una acción cada cierto tiempo. Por ejemplo, el resize de la ventana.

 

HTML:

   1:  <div style="height:100px;border:solid 2px;">
   2:      <div id='div1' style="position:relative;background-color:red;width:50px;height:50px;top:25px;" />
   3:  </div>

JS:

   1:  function SetupPosition(){
   2:      var div1 = document.getElementById('div1');
   3:      var parentContainer = div1.parentElement;
   4:      var leftValue = (parentContainer.offsetWidth / 2) -
   5:                      (div1.offsetWidth / 2);
   6:      div1.style.left = leftValue+"px";
   7:  }
   8:   
   9:  function OnWindowResize() {
  10:      /// <summary>Handler for the window resize event</summary>
  11:      
  12:      if (OnWindowResize.TimerId) { // If the timer has already been set
  13:          // Clear it in order to avoid multiple executions
  14:          window.clearTimeout(OnWindowResize.TimerId);
  15:      }
  16:      // Set a timeout to calculate the element position
  17:      OnWindowResize.TimerId = window.setTimeout(SetupPosition, 500);
  18:  }
  19:   
  20:  // Handle the window resize Event
  21:  window.onresize = OnWindowResize;

Pruébalo en JS Fiddle: http://jsfiddle.net/3DNBk/

 

La función OnWindowResize comprueba que exista una ejecución previa del window.setTimeout “mirando” en su propiedad TimerId.

Si la hay, cancela la ejecución, y vuelve a planificar otra para dentro de medio segundo.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *