event inside custom object can't access object's property

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • andrux
    New Member
    • Mar 2009
    • 2

    #1

    event inside custom object can't access object's property

    Hi,

    I'm having a hard time by trying and decipher this one. I tried googling around but couldn't come up with an answer (may be I just don't know the proper search terms)

    I wrote a custom object, and inside this object I set an onfocus event for a newly created input box (I changed it for an onclick for test purposes), the function inside this event needs to use one of the properties of the object, but it just can't. It keeps getting "undefined" value.

    Here's a part of the code:

    Code:
    function customObject() {
        this.myProperty = "testProperty";
        var t = document.createElement("INPUT");
        t.setAttribute("type", "text");
        document.body.appendChild(t);
        t.onclick = 
            function() {
                alert(this.myProperty);
            };
    }
    What I want to accomplish, is to get the value of "testProper ty" inside the t.onclick event, but if I reference "this" inside the event, it takes the actual input box (which is correct, of course). I managed to use a variable to hold the value I want, and I can use it that way, but I want to avoid that if possible (just out of recklessness).

    Do you have any ideea how this can be done?

    Thanks
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    by a closure.
    Code:
    function customObject() {
        this.myProperty = "testProperty";
        var t = document.createElement("INPUT");
        t.setAttribute("type", "text");
        document.body.appendChild(t);
        var co = this;
        t.onclick = function() {
                alert(co.myProperty);
        };
    }

    Comment

    • andrux
      New Member
      • Mar 2009
      • 2

      #3
      That worked perfectly!

      Thank you very much, Dormilich

      Comment

      Working...