只有两种变量:
- 全局变量:全局变量只不过是一个窗口级别的范围。
- 局部变量:在函数里定义的变量为局部变量,局部变量只在函数内有效。
全局变量:
全局变量正如全球明星(成龙,纳尔逊·曼德拉)。您可以从应用程序的任何部分访问它们(获取或设置值)。全局函数就像全球事件(新年,圣诞节)。您可以从应用程序的任何部分执行(调用)它们。
//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
变量作用域示例:
1.全局变量
var a = 1;
// global scope
function one() {
alert(a); // alerts \'1\'
}
2.局部变量
var a = 1;
function two(a) {
alert(a); // alerts the given argument, not the global value of \'1\'
}
// local scope again
function three() {
var a = 3;
alert(a); // alerts \'3\'
}
3.中间变量
中没有块范围
示例1:
var a = 1;
function four() {
if (true) {
var a = 4;
}
alert(a); // alerts \'4\', not the global value of \'1\'
}
示例二:
var a = 1;
function one() {
if (true) {
let a = 4;
}
alert(a); // alerts \'1\' because the \'let\' keyword uses block scoping
}
示例三:
var a = 1;
function five() {
this.a = 5;
}
alert(new five().a); // alerts \'5\'
4.闭包中的变量作用范围
var a = 1;
var six = (function() {
var a = 6;
return function() {
// \"closure\" means I have access to \'a\' in here,
// because it is defined in the function in which I was defined.
alert(a); // alerts \'6\'
};
})();
5.基于原型的变量范围
var a = 1;
function seven() {
this.a = 7;
}
// [ ].prototype.property loses to
// [ ].property in the lookup chain. For example...
// Won\'t get reached, because \'a\' is set in the constructor above.
seven.prototype.a = -1;
// Will get reached, even though \'b\' is NOT set in the constructor.
seven.prototype.b = 8;
alert(new seven().a); // alerts \'7\'
alert(new seven().b); // alerts \'8\'
6.一个额外的复杂案例(局部变量和全局变量)
var x = 5;
(function () {
console.log(x);
var x = 10;
console.log(x);
})();
以上示例打印出undefined和10而不是5和10,因为x在函数中已经被重新定义了,以上代码等于:
var x = 5;
(function () {
var x;
console.log(x);
x = 10;
console.log(x);
})();
7.Catch子句变量作用域
var e = 5;
console.log(e);
try {
throw 6;
} catch (e) {
console.log(e);
}
console.log(e);
将打印出来5,6,5。catch子句内部e隐藏全局变量和局部变量。但这个特殊的范围只适用于被捕获的变量。如果您var f;在catch子句中写入,那么它与在try-catch块之前或之后定义的完全相同。
继续阅读与本文标签相同的文章
上一篇 :
人脑连接互联网,请慎之又慎
下一篇 :
javascript如何获取数组和对象的值
-
微软建议企业客户卸载KB4520062累积更新
2026-05-14栏目: 教程
-
他让我国芯片研究停滞13年,还骗走11亿研发资金,现状如何?
2026-05-14栏目: 教程
-
健乐教学机器人可开展的教学实训内容
2026-05-14栏目: 教程
-
5G套餐曝光遭“吐槽”,iphone11受追捧,导致苹果11销量比较高
2026-05-14栏目: 教程
-
为什么修电脑的叫自己不要杀毒和清理垃圾?
2026-05-14栏目: 教程
