Accessing 'this' from event handler in a class

Discussion in 'JavaScript' started by bforbes, Sep 19, 2006.

  1. #1
    I'm trying to encapsulate some code in a class, but I can't access the 'this' object from within an event handler, since 'this' has the event target in it.

    
    function MyClass() {
        this.foobar="hello";
        this.create=function() {
            var newSpan=document.createElement('span');
            newSpan.innerHTML='sometext';
            newSpan.onmouseup=this.SPANonmouseup;
            document.body.appendChild(newSpan);
        }
        this.SPANonmouseup=function (e) {
            alert(this.foobar);
            alert(this);
        }
    }
    
    Code (markup):
    The first box reads 'undefined', the second reads '[object HTMLSpanElement]'. How can I access the class variables from an encapsulated event handler?
     
    bforbes, Sep 19, 2006 IP
  2. bforbes

    bforbes Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I found the solution. Declare a private variable within the class, and assign 'this' to it in the constructor. Private variables have scope in all class functions:
    
    function MyClass() {
        [b]var t=this;[/b]
        this.foobar="hello";
        this.create=function() {
            var newSpan=document.createElement('span');
            newSpan.innerHTML='sometext';
            newSpan.onmouseup=this.SPANonmouseup;
            document.body.appendChild(newSpan);
        }
        this.SPANonmouseup=function (e) {
            alert(t.foobar);
        }
    }
    
    Code (markup):
     
    bforbes, Sep 19, 2006 IP