如何处理包含其他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, false);
},
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 \”意味着事件处理程序中还有其他内容。有小费吗?
没有找到相关结果
已邀请:
4 个回复
钨蜡唤喉晤
。 您还使
依赖于某些全局变量,并且此函数的整体工作可能不再那么清楚。 只需在适当的上下文中致电
:
在支持ECMAScript 5的浏览器中,您还可以使用
[docs](请参阅其他浏览器的实现链接)来绑定元素
,这应参考:
逝媳蘑贩茄
然后可以使用函数“ boundHandler \”来处理事件,并且始终使用引用正确对象的“ 8”来设置实际代码。 较新的浏览器中还有一个名为\“。bind()\”的函数,可让您执行相同的操作。
舶啥戚
尝试
淘圃跺枯替