最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

In Javascript, global variable is not changing value inside a function - Stack Overflow

programmeradmin6浏览0评论
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?

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?

Share Improve this question edited Feb 2, 2015 at 1:16 Salman Virk asked Feb 2, 2015 at 1:13 Salman VirkSalman Virk 12.3k9 gold badges38 silver badges47 bronze badges 1
  • 1 stackoverflow./questions/15057649/… – Robert Commented Feb 2, 2015 at 1:29
Add a ment  | 

3 Answers 3

Reset to default 7

A function name and a variable are essentially the same thing in Javascript. You can declare a function via:

var a = function () {};

Which is the same as function a() {} for most intents and purposes. 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. It makes no difference whether this local a was defined via var a or 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. The higher scoped a is not touched by this inner assignment.

If the outer a definition is in the global scope, then you could assign to it with:

 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.

JavaScript is different from other languages:

JavaScript® (often shortened to JS) is a lightweight, interpreted, object-oriented language with first-class functions

What is 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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论