如何解决如何处理包含其他JavaScript对象的JavaScript对象中的“ this”?
| 我正在使用John Resig的出色javascript类来实现简单的javascript继承,并且我不禁烦恼一些与\'this \'关键字有关的变量范围问题。 我的延伸课程看起来像这样var EUNode = Class.extend({
// Methods
//-------------------------------------------------------------------------------
init : function(){
this.div = this.createDiv();
this.canDoStuff = true;
this.div.addEventListener(touchstart,this.touchStartHandler,false);
},// Create Div
//-------------------------------------------------------------------------------
createDiv : function(){
// code to create a DIV element,add some classes and do some
// other useful stuff
},touchStartHandler : function(event){
// In here,\'this\' refers to the div element,so the
// following condition doesn\'t work
if(this.canDoStuff){
// do some stuff
}
}
});
我需要能够从ѭ1内引用EUNode实例,因此我尝试了以下操作
var EUNode = Class.extend({
// Methods
//-------------------------------------------------------------------------------
init : function(){
this._super();
// Store a reference to \'this\' globally
self = this;
self.div = this.createDiv();
self.canDoStuff = true;
self.div.addEventListener(touchstart,self.touchStartHandler,touchStartHandler : function(event){
if(self.canDoStuff){
// Now I can do stuff,but \'self\' is now a global variable
// which isn\'t what I want. If there\'s more than one instance
// of EUNode,\'self\' references the newest instance.
}
}
});
所以我陷入了循环。似乎为了全局限制\“ self \\”的范围,我需要使用\“ this \”关键字,但是\“ this \”意味着事件处理程序中还有其他内容。有小费吗?
解决方法
是的,全局变量是错误的(通常)。如您所知,如果您有两个EUNode实例,您将已经遇到麻烦,因为最后一个实例将覆盖全局
self
。
您还使touchStartHandler
依赖于某些全局变量,并且此函数的整体工作可能不再那么清楚。
只需在适当的上下文中致电touchStartHandler
:
init : function(){
var self = this; // <- local `self`
this.div = this.createDiv();
this.canDoStuff = true;
// pass a closure,making `self` available inside the function
this.div.addEventListener(touchstart,function(event) {
self.touchStartHandler(event);
},false);
},
在支持ECMAScript 5的浏览器中,您还可以使用.bind()
[docs](请参阅其他浏览器的实现链接)来绑定元素this
,这应参考:
this.div.addEventListener(touchstart,this.touchStartHandler.bind(this),false);
, 建立事件处理程序时,只需将对“ touchStartHandler()\”的调用包装在一个匿名函数中,这样就可以通过类的相应实例对其进行调用。
换一种说法:
var boundHandler = function(event) { yourInstance.touchStartHandler(event); };
然后可以使用函数“ boundHandler \”来处理事件,并且始终使用引用正确对象的“ 8”来设置实际代码。
较新的浏览器中还有一个名为\“。bind()\”的函数,可让您执行相同的操作。
, 代替
self.div.addEventListener(touchstart,self.touchStartHandler,false);
尝试
self.div.addEventListener(touchstart,function(event) { self.touchStartHandler(event) },false);
, self.touchStartHandler.bind(self)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。