0

I have a test.html which includes tree.js.

in this HTML I have

<div id='forObj'></div>
<script type='text/javascript'>
var obj = new Tree(document.getElementById('forObj');
</script>

Inside the Tree.js File I have a function called

this.draw
...
else
            {

                    div.onclick = function(){obj.eventFoo(this.id);};

            }

...

my Problem is: Now everyone has to refer to the Object obj, or this will not work.

How can I generalize it, so the Object can get every name the coder wants to use?

Nathan Basanese
  • 8,475
  • 10
  • 37
  • 66
SepGuest
  • 127
  • 1
  • 11

1 Answers1

0

Just define your own obj variable with the current instance, using closure for the event listener:

… else {
    var obj = this;
    div.onclick = function(e) {
        obj.eventFoo(this.id);
    };
}

See also How to access the correct `this` context inside a callback? for a very similar manifestation of the problem (though you want to use the this of the handler).

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375