当前位置: 首页 > 图文教程 > 网络编程 > Javascript > javascript 变量作用域 代码分析

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 javascript 变量作用域 代码分析


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 412 ::
收藏到网摘: n/a

作用域(scope)是javascript中一项令人棘手的的特性。所有面向对象编程语言都有某种形式的作用域,不过和把这个概念放在什么上下文中有关。在javascript里,作用域是由函数划分的。 代码清单1-1 展示javascript的变量作用域的例子
//设置全局变量foo,并置为"test"
var foo = "test";
//在if块中
if(true){
//将foo置为'new test'
var foo = "new test";
}
//如我们所见,现在foo等于'new test'了
alert(foo == "new test");
//创建一个会修改变量foo的新函数
function test(){
var foo = "old test";
}
//然而在调用时,foo只在函数作用域内起作用
test();
//这里确认了foo 还是等于'new test'
alert(foo == "new test");
基于浏览器的javascript 的一个有趣的特性是,所有属于全局变量作用域的变量其实都是window对象的属性。
代码清单1-2 javascript中全局作用域和window对象
//一个全局作用域下的变量,存储了字符串'test'
var test = 'test';
//你可以看到我们的全局变量和window对象的test属性是一致的
alert(test == window.test)
最后如果变量没有显式定义,它就是全局定义的,虽然它可能只在这个函数作用域的范围内使用。
代码清单1-3 隐式全局作用域的变量声明
//一个设置了foo值的函数
function test(){
foo = "test";
}
//调用此函数以设置foo的值
test();
//我们发现foo现在是全局作用域下
alert(window.foo == "test");