当前位置: 首页 > 图文教程 > 网络编程 > Javascript > Javascript 陷阱 window全局对象

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 陷阱 window全局对象


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

ff和ie6下都是同样的运行结果,看来不是bug,那究竟是为什么呢? 注意到:对象方法访问其对象的属性时|必须|加以this.(和java不一样). function Test(){
this.name='Test';
var name=2;
this.show=function(){
alert(name);
alert(this.name);//显示名字
}
}
var test=new Test();//通过构造器创建一个对象
test.show();//输出2和'Test' ,说明对象方法访问其属性时必须加this.
function Test2(){
this.name='Test2';
this.show=function(){
alert(name);
alert(this.name);
}
}
Test();//直接调用Test();
var test2=new Test2();
test2.show();//输出了Test,Test2,很奇怪啊,name问什么有值了,而且怎么会是'Test',bug?
alert(name);
window.show(); //输出2,test;怎么会有show函数呢,难道是bug
//依次输出2,Test;Test,Test2;Test;2,Test
// ff和ie6下都是同样的运行结果,看来不是bug,那究竟是为什么呢?
// 注意到:对象方法访问其对象的属性时|必须|加以this.(和java不一样).
// 整个页面是默认的是|window|对象,那么定义的函数,默认就是window对象的方法。
//直接直接调用函数时,相当于通过window.调用方法,那么方法内部的this自然就是\
//window对象,this.name='Test'就是为window对象加了一个属性.
// 那么当方法局部作用域内未定义name且调用alert(name),就相当于调用alert(window.name);
/*啊,代码混乱了。这看起来像一个很严重的陷阱!!*/