доступ к переменной внутри функции в JavaScript - PullRequest
0 голосов
/ 25 июня 2018

Например, у меня есть эта функция JavaScript:

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}
  });
}

теперь мне нужно получить доступ к переменной «crop» для использования в этих кодах:

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

Поскольку второй блок кода, который я здесь написал, не в той же функции, как я могу получить доступ к переменной «crop» в функции createCroppie?

Ответы [ 2 ]

0 голосов
/ 25 июня 2018

Переменные функции находятся внутри функции, если не используется замыкание. Как указал Сенал, первое решение - использовать глобальную область видимости для переменной.

Чтобы переписать с помощью замыкания:

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();

Поиск документации Croppie основан на создании замыкания для возврата объекта с его переменными. Не нужно оборачивать функцию вокруг него.

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}
      };

Однако вы можете использовать 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}
  }
  function say(message) {
       console.log(message);
       return this;
  }
  return this;
  );
}

crop = createCroppie();

Теперь обрезка - это новый croppie с функцией журнала, и это (это следующие элементы, а не элементы объекта функции) работает.

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

Обратите внимание, что функция say функции закрытия должна возвращать "this" (Javascript this), чтобы включить функцию .result, позволяющую существовать crop.log.result ().

0 голосов
/ 25 июня 2018

Предполагая, что вы инициализируете Croppie до события click, вы можете сделать следующее

var myCroppie;

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

 createCroppie();

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