Javascript_备忘录3
2013-01-03 10:36
369 查看
今天备忘的是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" }
相关文章推荐
- JavaScript备忘录(1)——内置类型
- JavaScript备忘录(1)——内置类型
- javascript 备忘录
- JavaScript备忘录(2)——闭包
- JavaScript备忘录-逻辑运算符
- JavaScript备忘录-闭包
- Javascript备忘录-枚举一个对象的所有属
- javascript基础语法备忘录-变量和数据类型
- JavaScript学习笔记(备忘录)
- doT.js——前端javascript模板引擎问题备忘录
- doT.js——前端javascript模板引擎问题备忘录
- JavaScript效果备忘录之输入后显示提示
- Javascript_备忘录4
- [技术备忘录]javascript 自动完成(jQuery方式) - 安羽. - 博客园
- JavaScript备忘录-闭包(2)
- JavaScript备忘录(0106更新ing......)
- Javascript_备忘录6
- Javascript_备忘录1
- 备忘录:推荐13款JavaScript图形和图表绘制工具
- 备忘录:javascript通过url向jsp页面传递中文参数乱码解决方法