This keyboard pointing to different objects

Hi Forum,

Now this is a little advanced so I don’t expect many people will have the answer, but here goes anyways:

Here is a function I created to make event listening browser compatible:

function attachEventListener(node,type,functionRef,capture){
if(typeof node.addEventListener!=='undefined'){
node.addEventListener(type,functionRef,capture);
}
else if(typeof node.attachEvent!=='undefined'){
node.attachEvent('on'+type,functionRef);	
}
else{
node['on'+type]= functionRef();	
}
}

Now I have called this function from inside an object method called attachListener() and have attached a click event to a button I created:

attachEventListener(this.element,'click',this.gogo,false);

Now when I click the button the method basically alerts: this, (the keyword this) and points as you would expect to the button element I created and alerts [HTMLInputElement].

However when I use this code I get a different result:

var self = this;
attachEventListener(this.element,'click',function(){self.gogo()},false);

Now this points to the object of the method attachListener() and alerts [object Object].

I’m really confused as to why this is, I mean I’m thinking it has somethig to do with scope but I’m not sure, can someone explain this?

Thanks
Robbie Denton

In cases where addEventListener supported and called, you can preserve this by using:

attachEventListener( this.element, 'click', function(){ _self.gogo.call( this ); }, false );

However this will not apply if attachEvent is called, when this will point to window.