Javascript_备忘录3

今天备忘的是Variable Declaration and Variable Scope。今天直接上原汁原味的代码例子反而觉得更清楚:

var scope = "global"; // Declare a global variable
function checkscope() {
var scope = "local"; // Declare a local variable with the same name
return scope; // Return the local value, not the global one
}
checkscope() // => "local"
scope = "global"; // Declare a global variable, even without var.
function checkscope2() {
scope = "local"; // Oops! We just changed the global variable.          最重要的是这里,在函数体内没使用var,则修改的是全局变量。
myscope = "local"; // This implicitly declares a new global variable.
return [scope, myscope]; // Return two values.
}
checkscope2() // => ["local", "local"]: has side effects!
scope // => "local": global variable has changed.
myscope // => "local": global namespace cluttered up.
//这里主要讲函数可以嵌套
var
scope = "global scope"; // A global variable function checkscope() { var scope = "local scope"; // A local variable function nested() { var scope = "nested scope"; // A nested scope of local variables return scope; // Return the value in scope here } return nested(); } checkscope() // => "nested scope"
//这个例子很重要,说明了变量声明范围遍布了整个函数体,所以局部变量屏蔽了全局变量,但是注意这里的变量初始化,他发生在声明代码之后的范围,之前的范围是没初始化的。
var
scope = "global"; function f() { console.log(scope); // Prints "undefined", not "global" var scope = "local"; // Variable initialized here, but defined everywhere console.log(scope); // Prints "local" }

 

转载于:https://www.cnblogs.com/Key-Ky/archive/2013/01/03/2842727.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值