★★★javascript的this问题

lanytin 2009-11-18 04:51:47
<script type="text/javascript">
function GG(){
this.something = 200;
alert(this.something); // 1,200
function G1(){
alert(this.something); //2,100
function G2(){
alert(this.something); //3,100
}
G2();
}
G1();
}
something = 100;
var g = new GG();
</script>

g=new GG()时,执行GG()的构造函数,GG()中this.something=200,this指向g,
1处的this.something=200,为什么2,3处的this.something=100呢,这时this指向谁呢?同在GG()
内部,1处的this和2,3处的this为什么不同?
...全文
81 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
xiaofan_sap 2009-11-18
  • 打赏
  • 举报
回复
http://xiaofeizm55333.javaeye.com/blog/80913 看看这个 从作用域的角度去考虑 就明白了 ~~
lanytin 2009-11-18
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 lanytin 的回复:]
谢谢xiaofan的回答,有一点明白了。但还有一个问题,
是关于call()的。
function GG(){
this.something = 200;
alert(this.something); // 200
function G1(){
alert(this.something); //200
function G2(){
alert(this.something); //200
}
G2.call(this);
}
G1.call(this);
}
something = 100;
var g = new GG();

当G1.call(this)时,G1为什么会有call()的方法呢?它继承了某些对象吗?
函数的执行,要么是new的时候,要么是GG()执行,G1.call(this)这样写,为什么
会执行G1的方法呢?
[/Quote]
lanytin 2009-11-18
  • 打赏
  • 举报
回复
谢谢xiaofan的回答,有一点明白了。但还有一个问题,
是关于call()的。
function GG(){
this.something = 200;
alert(this.something); // 200
function G1(){
alert(this.something); //200
function G2(){
alert(this.something); //200
}
G2.call(this);
}
G1.call(this);
}
something = 100;
var g = new GG();
</script>
当G1.call(this)时,G1为什么会有call()的方法呢?它继承了某些对象吗?
函数的执行,要么是new的时候,要么是GG()执行,G1.call(this)这样写,为什么
会执行G1的方法呢?
xiaofan_sap 2009-11-18
  • 打赏
  • 举报
回复

在函数里的this只有两种指向,当指明调用对象的时候,他就指向该调用对象,如果没有指向该调用对象,就是window全局对象,var g = new GG();所以他里面的this指向g,
但是G2(),G1(),都没有调用对象,就指向了window,something=100,就是window.something=100,所以是弹出来100


87,923

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧