在 JavaScript 中访问函数内部的变量

access to a variable inside the function in JavaScript

例如我有这个 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');
      });
    }); 

由于我在这里写的第二个代码块不在同一个函数中,我如何访问 createCroppie 函数中的 "crop" 变量?

假设你在点击事件之前初始化了Croppie,你可以进行如下操作

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

函数变量在函数范围内,除非使用闭包。正如 Senal 指出的那样,第一个解决方案是为变量使用全局范围。

使用闭包重写:

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 文档,它是基于为 return 对象及其变量创建一个闭包。无需围绕它包装函数。

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

但是,您可以使用闭包来扩展库。

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

现在 crop 是一个带有 log 函数的新 croppie,并且这个(以下不是函数对象的元素)有效。

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

注意,闭包函数的say函数需要return"this",(Javascript这个),这样才能包含.result函数允许crop.log.result () 存在。