- 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);
- /*啊,代码混乱了。这看起来像一个很严重的陷阱!!*/
Javascript 陷阱-window全局对象
最新推荐文章于 2023-05-13 11:58:27 发布