在本地重新分配全局变量,而不在全局范围内更改它们。的JavaScript

时间:2018-12-13 17:12:53

标签: javascript scope global-variables

我知道如何使代码按预期工作,但是我尝试使用相同的变量名并遇到以下问题:

是否可以在submitSettings()中重新分配最小和最大变量,以便在全局范围内保持不变? (您可以在代码中看到为什么我希望它们在全局范围内保持不变。)

如果是,请告诉我如何以及在哪里可以了解有关此主题的更多信息。

  // here i get the HTML elements from <input>.
  let min = document.getElementById('min')
  let max = document.getElementById('max')

  function submitSettings() {
    // here i want to validate the values from those HTML elements while maintaining the same variable names (min, max).
    function validateSettings() {
      min = min.valueAsNumber // My question: How can i reassign global variables locally without changing them in global scope?
      let max = max.valueAsNumber // Or: How can i get max variable from the scope from outside (from global scope)?

      min >= max ? console.log("Not good") : console.log("OK")
    }

    validateSettings()

    // here i want to clear <input>, but i can't because min and max are not HTML elements anymore, rather numbers.
    min.value = ''
    max.value = ''
  }

1 个答案:

答案 0 :(得分:1)

阴影变量通常被认为是不好的做法,原因是您的代码突出显示了原因。从一个范围到另一个范围很难维护。解决此问题的方法有多种,但是它们主要依靠为本地上下文重命名变量。

// here i get the HTML elements from <input>.
  const min = document.getElementById('min')
  const max = document.getElementById('max')

  function submitSettings() {
    // here i want to validate the values from those HTML elements while maintaining the same variable names (min, max).
    function validateSettings() {
      let minValue = min.valueAsNumber // My question: How can i reassign global variables locally without changing them in global scope?
      let maxValue = max.valueAsNumber // Or: How can i get max variable from the scope from outside (from global scope)?

      minValue >= maxValue ? console.log("Not good") : console.log("OK")
    }

    validateSettings()


    min.value = ''
    max.value = ''
  }

严格来说,let关键字是唯一的,因为它创建了块范围的变量,因此允许以下内容

const global = 1;
const local = () => {
  let global = 2;
  console.log(global);
}

local(); // logs 2
console.log(global); // logs 1

但是我认为这不是很好的做法

您还可以使用validateSettings是一个函数并对它进行minmax自变量的事实。

// here i get the HTML elements from <input>.
  const min = document.getElementById('min')
  const max = document.getElementById('max')

  function submitSettings() {
    // here i want to validate the values from those HTML elements while maintaining the same variable names (min, max).
    function validateSettings(min, max) {    
      min >= max ? console.log("Not good") : console.log("OK")
    }

    validateSettings(min.value, max.value)


    min.value = ''
    max.value = ''
  }