[英]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引擎,从上至下阅读以下代码:
numPrinter
function. numPrinter
函数。 There are no ()
present, so numPrinter
is only defined but not invoked. ()
,因此numPrinter
仅被定义而不被调用。 console.log(i);
console.log(i);
is read. 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
暂时还无法访问。 numPrinter();
numPrinter();
Here, the JS engine reads the ()
and invokes the numPrinter
function. ()
并调用numPrinter
函数。 We now have access to i
because undeclared variables always become global variables. i
因为未声明的变量始终成为全局变量。 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.