I’m using John Resig’s excellent javascript class for simple javascript inheritance and I’m having a spot of bother getting my head around some variable scope problems in relation to the ‘this’ keyword.
My extended class looks a little like 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
}
}
});
I need to be able to reference the EUNode instance from inside the touchStartEventHandler, so I tried the following
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.
}
}
});
So I’m stuck in a loop. It seems that in order to limit the scope of “self” globally, I need to use the “this” keyword, but “this” means something else inside event handlers. Any tips?
Yes, global variables are bad (in general). As you noticed yourself, you already get in trouble if you have two EUNode instances because the last one would override the global
self.You are also making
touchStartHandlerdependent on some global variable, and the whole working of this function might not be so clear anymore.Just call
touchStartHandlerin the right context:In browsers supporting ECMAScript 5 you can also use
.bind()[docs] (see link for an implementation for other browsers) to bind the elementthisshould refer to: