如何从JavaScript嵌套函数中访问全局变量?

huangapple go评论60阅读模式
英文:

how to access global variable from nested function in javascript

问题

我有以下的代码来访问嵌套函数dd中的全局变量a,但我只能从abc中访问a。如何从dd函数中访问a=6。

var a = 6;
function abc() {
  var a = 10;
  a += 1
  console.log(a)
  function dd() {
    a += 1
    console.log(a)
  }
  dd()
}
abc();
英文:

I have the following code to access global variable a from the nested function dd. but i am only able to access a from abc. How can we access a=6 from dd function.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var a = 6;
function abc() {
  var a = 10;
  a += 1
  console.log(a)
  function dd() {
    a += 1
    console.log(a)
  }
  dd()
}
abc();

<!-- end snippet -->

答案1

得分: 4

不要遮蔽变量。(即,将在abc内定义的a重命名为不同的名称)。

使用一个带有检查遮蔽的规则的代码检查工具(linter)。


由于您尝试访问的变量是全局变量(不是最佳实践)并且使用了var(也不是最佳实践),所以您可以(如果代码在<script>元素中运行)使用window.a来访问它。不过,重构您的代码以避免遮蔽是更好的选择。

英文:

Don't shadow variables. (i.e. rename the a defined inside abc to use a different name).

Do use a linter with a rule to test for shadowing.


Since the variable you are trying to access is a global (not best practise) and uses var (also not best practise) then you can (if the code in running in a &lt;script&gt; element) access it with window.a. Refactoring your code to avoid shadowing is a better bet though.

答案2

得分: 0

发生的情况是关于作用域的概念。

变量a在全局作用域中声明并初始化为6的值。然后,您创建了一个名为abc的函数,然后创建了另一个名为a的变量,并为其赋值为10。

这不是最佳做法,也不建议这样做,因为它可能导致意外行为。值为6的变量可以从任何地方访问,而值为10的变量只能在函数abc内或在其中的任何函数内部访问。

英文:

What's taking place here is a concept about scope.

The variable a is declared in the global scope and initialised with the value of 6. Then you created a function named abc and then created another variable named a and gave it a value of 10.

This is not best practice and it's not recommended because it can cause unintended behaviour. The variable with the value 6 can be accessed from anywhere then the variable with the value 10 can only be accessed from anywhere as long as it is within the function abc or any function which is inside it.

答案3

得分: -1

以下是翻译好的部分:

... and if you really need this:

var a = 6;
function abc(copy = a) {
  var a = 10;
  a += 1
  console.log(a)
  function dd() {
    copy += 1
    console.log(copy)
  }
  dd()
}
abc();
英文:

... and if you really need this:

var a = 6;
function abc(copy = a) {
  var a = 10;
  a += 1
  console.log(a)
  function dd() {
    copy += 1
    console.log(copy)
  }
  dd()
}
abc();

huangapple
  • 本文由 发表于 2023年6月12日 21:41:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76457263.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定