How to fix the error function not defined

0

Hello, I have the following function:

function comprobarCondicion(opcion) {
      this.value = opcion;

      if (opcion == '164.132.203.28:455') {

      }
}

If I put it in index.html , it works for me and if I put it in my main .js it does not work, just in case if I'm calling js from the index.

<script type="text/javascript" src="js/mt6.js"></script>

and I call it in onchange to the function.

onchange="comprobarCondicion(this.value)"

Well anyway, the error is that the function appears to me as undefined if I put it in my .js and if I put it in the index.html it goes all good.

    
asked by Eduardo Campos 10.02.2017 в 21:27
source

1 answer

3

Your error is because you have the function within an IIFE ( Immediately invoked function expression ):

// IIFE
(function () {
  ...
  // no es visible fuera
  function comprobarCondicion (value) {
    ...
  }
})();

These types of functions are executed immediately once they are read. Given that comprobarCondicion is within the IIE, is not visible outside it, therefore, when in the pairing stage it is about finding comprobarCondicion in the scope of window , it fails, since, obviously, it is not there.

You must remove the function and put it out of the IIFE:

(function () {
  ...
})();

function comprobarCondicion (value) {
  ...
}
  

If I put the function out I can not use the variables that are inside?

No, you can not, because var has a scope of function that is, in this case, the IIFE. Something better you can do is the following: within the IIFE, add the listener for change to the desired element.

(function () {
  var algo = 'algo';
  var otraCosa = 'otraCosa';
  var otraMas = 'otra Mas');

  ...

  // cambia aquí por el id de tu elemento
  $('#selectCondicion').on('change', function (e) {
    if($(this).val() === '164.132.203.28:455') {
      // hacer algo
    }
  });
})();
    
answered by 10.02.2017 / 23:40
source