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'){
else if(typeof node.attachEvent!=='undefined'){
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:


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;

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?

Robbie Denton

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

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

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