简体   繁体   English

为什么函数内的javascript全局变量显示错误?

[英]why does a javascript global variable within function show an error?

I put a global variable within numPrinter function in Javascript. 我在Javascript的numPrinter函数中放入了一个全局变量。
but if I don't put numPrinter(); 但是如果我不放numPrinter(); before putting console.log(i); 在放置console.log(i);之前console.log(i);


it is a global variable .. global .. and also I don't understand how global variable works after numPrinter() 它是a global variable .. global ..而且我不明白numPrinter()之后global variable是如何工作的

there's no return i; return i;没有return i; within numPrinter(); numPrinter();

var numPrinter = function(){

    i = 30;
};

console.log(i);  // ReferenceError: i is not defined

numPrinter();
console.log(i);  // 30

Imagine you are the JavaScript engine, reading this code from the top-down: 假设您是JavaScript引擎,从上至下阅读以下代码:

  1. The first thing we read is the numPrinter function. 我们读的第一件事是numPrinter函数。 There are no () present, so numPrinter is only defined but not invoked. 目前没有() ,因此numPrinter仅被定义而不被调用。
  2. Continuing down, the first console.log(i); 继续向下,第一个console.log(i); is read. 被读取。 Calling it here results in ReferenceError: i is not defined because numPrinter still has NOT been invoked so i can't be accessed yet. 这里调用它导致ReferenceError: i is not defined ,因为numPrinter还没有被调用所以i暂时还无法访问。
  3. Further down, we encounter numPrinter(); 再往下,我们遇到numPrinter(); Here, the JS engine reads the () and invokes the numPrinter function. 在此,JS引擎读取()并调用numPrinter函数。 We now have access to i because undeclared variables always become global variables. 现在,我们可以访问i因为未声明的变量始终成为全局变量。
  4. Lastly, the second console.log(i); 最后,第二个console.log(i); is read and prints out the result of 30 because i is globally accessible outside of the numPrinter function. 被读取并打印出30的结果,因为在numPrinter函数之外可以全局访问i

By default variables in js are global, so if you write smth like: 默认情况下,js中的变量是全局变量,因此如果您将smth编写为:

let i = 30

in your function, it will be local 在您的功能中,它将是本地的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM