javascriptfunctioncroppie

access to a variable inside the function in JavaScript


For example I have this JavaScript function:

function createCroppie() {
  var crop = new Croppie(document.getElementById('js-image-editor'), {
      enableExif: true,
      showZoomer: true,
      viewport: { width: y, height: y, type: 'square'},
      boundary: { width: x, height: x}
  });
}

now I need to access to the "crop" variable for using in these codes:

  $('.fa-save').on('click', function (ev) {
       crop.result ({
        type: 'canvas',
        size: 'viewport'
      }).then(function () {
        console.log('upload image complete');
      });
    }); 

Since the second block of code that I wrote here is not in the same function, how can I access to the "crop" variable in createCroppie function?


Solution

  • Function variables are scoped within the function, unless closure is used. As Senal pointed out the first solution is to use a global scope for the variable.

    To rewrite using closure:

    function createCroppie() {
      var crop = new Croppie(document.getElementById('js-image-editor'), {
          enableExif: true,
          showZoomer: true,
          viewport: { width: y, height: y, type: 'square'},
          boundary: { width: x, height: x}
      }
      return crop;
    // or return this;
    // this being the elements of the function as an object.
      );
    }
    
    crop = createCroppie();
    

    Looking up Croppie documentation it is based on creating a closure to return a object with its variables. No need to wrap a function around it.

    var myCroppie = new Croppie(document.getElementById('js-image-editor'), {
              enableExif: true,
              showZoomer: true,
              viewport: { width: y, height: y, type: 'square'},
              boundary: { width: x, height: x}
          };
    

    However, you could use closure to extend the library.

    function createCroppie() {
      var crop = new Croppie(document.getElementById('js-image-editor'), {
          enableExif: true,
          showZoomer: true,
          viewport: { width: y, height: y, type: 'square'},
          boundary: { width: x, height: x}
      }
      function say(message) {
           console.log(message);
           return this;
      }
      return this;
      );
    }
    
    crop = createCroppie();
    

    Now crop is a new croppie with a log function, and this, (this being the following not the elements of the object of the function), works.

      $('.fa-save').on('click', function (ev) {
           crop.log('clicked').result ({
            type: 'canvas',
            size: 'viewport'
          }).then(function () {
            console.log('upload image complete');
          });
        }); 
    

    Note, the say function of the closure function needs to return "this", (Javascript this), so as to include the .result function allowing crop.log.result() to exist.