首页 > 解决方案 > 全局作用域如何在 javascript 中工作

问题描述

 var a = 10
 function fun(){
     var b = 20
 }
fun()

在此代码中, var a 具有全局范围,但 var b 没有全局范围但具有功能范围。但是由于 fun() 本身是全局函数,它将对任何地方都是全局的,为什么 var b 不是全局的

标签: javascriptvariablesscope

解决方案


A variable declared outside a function becomes GLOBAL. Variables inside the Global scope can be accessed and altered in any other scope.

Global Scope:

// global scope
var a = 1;

function one() {
  alert(a); // alerts '1'
}

Local scope:

// global scope
var a = 1;

function two(a) { // passing (a) makes it local scope
  alert(a); // alerts the given argument, not the global value of '1'
}

// local scope again
function three() {
  var a = 3;
  alert(a); // alerts '3'
}

Global scope lives as long as your application lives. Local Scope lives as long as your functions are called and executed.

Here, b is inside a function so b is a local variable and it has a local scope, and a is a global variable and it lives when the application lives, and b lives when fun() lives.


推荐阅读