Access var inside: img.onload = function ()

0

I want to access the result that is unlinked within the function that generates img.onload , or something that facilitates me to perform the function of checking the measurements using the following code:

I hope the idea of the code is clear link

    
asked by Rigoli 11.05.2017 в 18:00
source

1 answer

0

In javascript local variables have visibility only within the function where they are defined, that is, the functions define the visibility fields of the variables in javascript.

Therefore, in the code that you present the question would be like this:

$('#rPictures').on('change', function () {
  var sizeIsOK = ''  // acá definís la variable
                     // el ámbito de la misma es la función callback
  var size = 25

  for (i = 0; i < 2; i++) {
    if (size < 12) {
      sizeIsOK = 'menor' // la variable ya existe, por lo tanto no
                         // es necesario escribir:
                         //     var sizeIsOK = 'menor'
    } else if (size > 20) {
      sizeIsOK = 'mayor' // lo mismo acá
    }
  }
  console.log(sizeIsOK); // => 'mayor'

  // la variable sigue siendo visible porque no salimos de la función
  // para no perderla de vista la guardamos en algún lado:
  document.sizeIsOk = sizeIsOK
})

// después de correr el callback
console.log(sizeIsOK)          // => undefined
console.log(document.sizeIsOK) // => 'mayor'
    
answered by 04.10.2017 в 04:36