JavaScript中的this

[b]JavaScript中的this[/b]


随着函数使用场合的不同,this的值会发生变化。但是有一个总的原则,那就是this指的是,调用函数的那个对象。
this指向函数执行时的当前对象,值得注意,该关键字在Javascript中和执行环境,而非声明环境有关。


[b]情况一:纯粹的函数调用[/b]
属于全局性调用,因此this就代表全局对象Global(浏览器中就是window对象)
function test(){
    this.x = 1;
    alert(this.x);
}
test(); // 1


运行结果是1。
因为直接调用,所以this是对象Global


[b]情况二:作为对象方法的调用[/b]
函数还可以作为某个对象的方法调用,这时this就指这个上级对象。
function test(){
alert(this.x);
}
var o = {};
o.x = 1;
o.m = test;
o.m(); // 1


运行结果是1。
因为是o这个对象调用,所以this是对象是o


[b]情况三:作为构造函数调用[/b]
所谓构造函数,就是通过这个函数生成一个新对象(object)。这时,this就指这个新对象。
function test(){
this.x = 1;
}
var o = new test();
alert(o.x); // 1


运行结果是1。
构造函数调用,新建时this是新建的对象


[b]情况四:apply调用[/b]
apply()是函数对象的一个方法,它的作用是改变函数的调用对象,它的第一个参数就表示改变后的
调用这个函数的对象。因此,this指的就是这第一个参数。
var x = 0;
function test(){
alert(this.x);
}
var o={};
o.x = 1;
o.m = test;
o.m.apply(); //0


apply()的参数为空时,默认调用全局对象。因此,这时的运行结果为0,证明this指的是全局对象。
如果把最后一行代码修改为
o.m.apply(o); //1
运行结果就变成了1,证明了这时this代表的是对象o。


[b]javascript有一个设计缺陷,使得的this绑定混乱[/b]
var subway={
name:'1号线',
speed:0,
run:function(speed){
this.speed=speed; //绑定到对象本身
function test(speed){
this.speed=speed+50;//竟然绑定到全局变量了,真是匪夷所思啊
}
test(speed);
}
};
subway.run(100);
console.log(subway.speed);//100
console.log(speed);//150


解决方法约定用that代替this
var subway={
name:'1号线',
speed:0,
run:function(speed){
var that=this; //用that代替this
this.speed=speed;
function test(speed){
that.speed=speed+50;
}
test(speed);
}
};
subway.run(100);
console.log(subway.speed);//150



this指向函数[b]执行时的当前对象[/b],值得注意,该关键字在Javascript中和执行环境,而非声明环境有关。
举个例子来说明这个问题:
var someone = {
name: "Bob",
showName: function(){
alert(this.name);
}
};

var other = {
name: "Tom",
showName: someone.showName
}

other.showName();  //Tom


this关键字虽然是在someone.showName中声明的,但运行的时候是other.showName,所以this指向other.showName
函数的当前对象,即other,故最后alert出来的是other.name。


原文参考:[url]http://www.cnblogs.com/greenteaone/p/4193985.html[/url]
原文参考:[url]http://www.ruanyifeng.com/blog/2010/04/using_this_keyword_in_javascript.html[/url]
原文参考:[url]http://www.cnblogs.com/justany/archive/2012/11/01/the_keyword_this_in_javascript.html[/url]
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值