0

Possible Duplicate:
Referencing “this” inside setInterval/setTimeout within object prototype methods

The second alert box is saying "undefined"? Why is this?

<a id = "clickme">Click Me!</a>
<script>
var a = document.getElementById("clickme");
a.onclick = function(); {
    alert(this.innerHTML);
    setTimeout( function() {
        alert( this.innerHTML );
    }, 1000);
};
</script>
Community
  • 1
  • 1
wdebvrd
  • 33
  • 3

2 Answers2

3

Because inside the function you're passing to setTimeout, this is not the a element anymore. It will either be the global object (window in browser-land) or undefined in strict mode.

Instead, store a reference to this;

var a = document.getElementById("clickme");
a.onclick = function(); {
    var that = this;

    alert(this.innerHTML);
    setTimeout( function() {
        alert( that.innerHTML );
    }, 1000);
};
Matt
  • 74,352
  • 26
  • 153
  • 180
1

https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout#The_.22this.22_problem

this has a different value inside the setTimeout handler.

Amadan
  • 191,408
  • 23
  • 240
  • 301