java中this和that的区别_Javascript中的this,bind和that

Javascript中必须通过this来访问类成员,可是this的特点就是函数绑在哪个对象上,它就指向那个对象。这个可能困扰过很多的程序员,特别是从C#,Java等语言过来的程序员。

functionFoo(){this.message = 'This is message from Foo';

}

Foo.prototype.printMessage= function(){

console.log(this.message);

}functionFoo2(){this.message = 'This is message from Foo2';

}var foo = newFoo();

foo.printMessage();var foo2 = newFoo2();

foo2.printMessage=foo.printMessage;

foo2.printMessage();

输出为:

This is message from Foo

This is message from Foo2

主要原因就是this改变了,因此Javascript中this的用法,和C++\C#中的大为不同。如果需要传统方式使用this的函数,可以使用Function.prototype.bind(),指定函数的this值:

functionFoo(){this.message = 'This is message from Foo';this.printMessage = (function(){

console.log(this.message);

}).bind(this);

}functionFoo2(){this.message = 'This is message from Foo2';

}var foo = newFoo();

foo.printMessage();var foo2 = newFoo2();

foo2.printMessage=foo.printMessage;

foo2.printMessage();

输出为:

This is message from Foo

This is message from Foo

另外使用call和apply也可以改变函数调用时的this值。

bind函数的主要问题是IE9以后才开始提供。并且一旦开始习惯了Javascript的this用法,这种bind反而会不习惯。在实践中,更多用到的还是保存this:

functionFoo(){var that = this;this.message = 'This is message from Foo';this.printMessage = function(){

console.log(that.message);

};

}functionFoo2(){this.message = 'This is message from Foo2';

}var foo = newFoo();

foo.printMessage();var foo2 = newFoo2();

foo2.printMessage=foo.printMessage;

foo2.printMessage();

输出同上。

注意我们是通过that来访问的message(除了that,context和self也是常用的名称)。Javascript一个还算欣慰的地方就是他的闭包上下文始终是在函数定义的地方,因此不管函数被挂上哪个对象上,捕获到的that始终是这个。当然这个地方不算闭包,有闭无包,但原理是相同的。这也是实践中用的最多的方法,推荐使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值