[英]In Javascript, global variable is not changing value inside a function
var a = 1;
function b() {
function a() {}; // local scope
a = 10; // global scope
}
b();
alert(a);
It alerts 1 and not 10. I am wondering why is it so? 它警报1而不是10。我想知道为什么会这样吗?
A function name and a variable are essentially the same thing in Javascript. 函数名称和变量在Javascript中本质上是相同的。 You can declare a function via:
您可以通过以下方式声明函数:
var a = function () {};
Which is the same as function a() {}
for most intents and purposes. 在大多数情况下,它与
function a() {}
相同。 Both create a symbol in the current scope and make that symbol's value a function. 两者都会在当前范围内创建一个符号 ,并使该符号的值成为函数。
What you're doing is you're shadowing the global a
with your own local a
. 你在做什么是你的阴影,全球
a
用自己的本地a
。 It makes no difference whether this local a
was defined via var a
or function a
. 此局部变量
a
是通过var a
还是function a
定义的都没有区别。
Your code is the same as this: 您的代码与此相同:
var a = 1;
function b() {
var a = function () {}; // local scope
a = 10;
}
b();
alert(a);
Thus, the declaration of your local scope function creates a new local variable named a
that initially has a function assigned to it, but you then reassign it to the value of 10
. 因此,您的局部作用域函数的声明将创建一个名为
a
的新局部变量,该变量最初具有分配给它的函数,但随后将其重新分配为值10
。 The higher scoped a
is not touched by this inner assignment. 此内部分配未触及较高范围的
a
。
If the outer a
definition is in the global scope, then you could assign to it with: 如果外
a
定义是在全球范围内,那么你可以分配给它:
window.a = 10;
If it is not in the global scope, then it has been "hidden" by the inner definition of a
and there is no way to reach the outer a
directly from the inner scope. 如果它不在全局范围内,则它已被
a
的内部定义“隐藏”,并且无法直接从内部范围到达外部a
。
JavaScript is different from other languages: JavaScript与其他语言不同:
JavaScript® (often shortened to JS) is a lightweight, interpreted, object-oriented language with first-class functions
JavaScript®(通常缩写为JS)是一种轻量级,解释性,面向对象的语言,具有一流的功能
What is first-class
? 什么是
first-class
?
allows functions to be passed around just like any other value.
允许像其他任何值一样传递函数。
So as jfriend00 pointed out it converts the function into a variable locally in the function thus not changing the global variable. 因此,正如jfriend00指出的那样,它将函数转换为函数中的局部变量,因此不会更改全局变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.