SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Hybrid View

  1. #1
    SitePoint Member
    Join Date
    May 2012
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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:

    Code JavaScript:
    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:

    Code JavaScript:
    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:

    Code JavaScript:
    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

  2. #2
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In cases where addEventListener supported and called, you can preserve this by using:

    Code:
    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.
    Tab-indentation is a crime against humanity.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •