javascript中变量的范围是什么?它们在函数内部的作用域与在函数外部的作用域相同吗?或者这有关系吗?此外,如果变量是全局定义的,那么变量存储在哪里?
当前回答
在“Javascript 1.7”(Mozilla对Javascript的扩展)中,还可以使用let语句声明块范围变量:
var a = 4;
let (a = 3) {
alert(a); // 3
}
alert(a); // 4
其他回答
全球范围:
全球变量就像全球明星(成龙、纳尔逊·曼德拉)。您可以从应用程序的任何部分访问它们(获取或设置值)。全球功能就像全球活动(新年、圣诞节)。您可以从应用程序的任何部分执行(调用)它们。
//global variable
var a = 2;
//global function
function b(){
console.log(a); //access global variable
}
本地范围:
如果你在美国,你可能会认识金·卡戴珊(Kim Kardashian),她是臭名昭著的名人(她以某种方式制作了小报)。但美国以外的人不会认出她。她是当地的明星,与她的领地息息相关。
局部变量就像局部恒星。您只能在范围内访问它们(获取或设置值)。本地函数就像本地事件一样,只能在该范围内执行(庆祝)。如果您想从作用域之外访问它们,将出现引用错误
function b(){
var d = 21; //local variable
console.log(d);
function dog(){ console.log(a); }
dog(); //execute local function
}
console.log(d); //ReferenceError: dddddd is not defined
查看本文以深入了解范围
据我理解,关键是Javascript具有函数级作用域,而不是更常见的C块作用域。
这是一篇关于这个主题的好文章。
JavaScript只有两种类型的作用域:
全局作用域:全局只是一个窗口级作用域。在这里,整个应用程序中都存在变量。Functional Scope:在带有var关键字的函数中声明的变量具有函数作用域。
每当调用一个函数时,就会创建一个变量范围对象(并包含在范围链中),然后是JavaScript中的变量。
a = "global";
function outer(){
b = "local";
console.log(a+b); //"globallocal"
}
outer();
作用域链-->
窗口级别-a和外部函数位于范围链的顶层。当外部函数调用一个新的变量作用域对象(并包含在作用域链中)时,在其内部添加了变量b。
现在,当一个变量a需要时,它首先搜索最近的变量范围,如果变量不在,则将其移动到变量范围链的下一个对象。在这种情况下,这是窗口级别。
JS中只有函数作用域。不阻止范围!你也可以看到什么在提升。
var global_variable = "global_variable";
var hoisting_variable = "global_hoist";
// Global variables printed
console.log("global_scope: - global_variable: " + global_variable);
console.log("global_scope: - hoisting_variable: " + hoisting_variable);
if (true) {
// The variable block will be global, on true condition.
var block = "block";
}
console.log("global_scope: - block: " + block);
function local_function() {
var local_variable = "local_variable";
console.log("local_scope: - local_variable: " + local_variable);
console.log("local_scope: - global_variable: " + global_variable);
console.log("local_scope: - block: " + block);
// The hoisting_variable is undefined at the moment.
console.log("local_scope: - hoisting_variable: " + hoisting_variable);
var hoisting_variable = "local_hoist";
// The hoisting_variable is now set as a local one.
console.log("local_scope: - hoisting_variable: " + hoisting_variable);
}
local_function();
// No variable in a separate function is visible into the global scope.
console.log("global_scope: - local_variable: " + local_variable);
在“Javascript 1.7”(Mozilla对Javascript的扩展)中,还可以使用let语句声明块范围变量:
var a = 4;
let (a = 3) {
alert(a); // 3
}
alert(a); // 4
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何从Python函数中返回两个值?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- PowerShell:仅为单个命令设置环境变量
- 如何确保<select>表单字段被禁用时提交?