簡體   English   中英

此JavaScript代碼段的正確變量范圍是什么

[英]What is the correct variable scope for this Javascript snippet

我已經在下面編寫了函數。 我需要讀取圖像的尺寸,然后將其縮小。 初始回調后,我想使用計算出的widthheight值來調整大小和保存圖像。 我的變量不在范圍內,但出現了ReferenceError: width is not defined 如何正確確定這些變量的范圍,以便它們可用於resize功能?

  function saveImage(image) {
    return new Promise((resolve, reject) => {
      gm(image.data).size(function(error, value) {
        if (value.width > image.maxSize || value.height > image.maxSize) {
          max = Math.max(value.width, value.height);
          if (value.width == max) {
            width = image.maxSize; height = null;
          } else {
            height = image.maxSize; width = null;
          }
        } else {
          width = value.width; height = value.height;
        }
      })
      .resize(width, height)
      .write('./tmp/test.jpg', function(error, value) {
        if (!error) console.log(error);
      });;
    });
  }

您應該正確定義變量...我更喜歡您應該了解es6語法,並對變量使用“ let”和“ const”,范圍很廣,謝謝:-@ ravi

在promise中,您使用箭頭函數,但是在下面的.size()行中,您使用舊樣式的匿名函數,然后您失去了作用域。 您可以嘗試對.size()使用箭頭功能

.size((error, value) => {})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM