0

Here's a complete html document that demonstrates my problem:

<html>
<head>
    <title>Test</title>
</head>

<script type="text/javascript">
    function messageDisplayer(message) {
        this.alertMessage = message;
    }

    messageDisplayer.prototype.showMessage = function() {
        alert( this.alertMessage );
    };

    function start() {
        var displayer = new messageDisplayer("Show this message");
        displayer.showMessage();
       window.setTimeout( displayer.showMessage, 1000 );
    }
</script>

<body onLoad="start()">Test</body></html>

When this page is loaded, I immediately get a 'Show this message' alert, but when the timeout kicks in a second later, it gives an alert with 'undefined'. When I set a breakpoint on that alert, this is apparently the window itself, not my messageDisplayer object the second time it hits it.

How can I get that function to refer to the alertMessage property when it's called by timeout?

Arjan
  • 19,957
  • 2
  • 55
  • 48
Flynn1179
  • 11,925
  • 6
  • 38
  • 74
  • Yeah, you're quite right. If I'd known to call it a callback I'd probably have spotted that question myself. – Flynn1179 May 04 '16 at 10:40
  • As with a lot of things - once you get the right terminology it's easy! – James Thorpe May 04 '16 at 10:40
  • Actually you miss " () " , it should be `window.setTimeout( displayer.showMessage(), 1000 );` – Sachin K May 04 '16 at 10:53
  • @SachinK: No it shouldn't. That would call the function immediately and attempt to call the result of the function as a callback instead of the function itself. – Flynn1179 May 04 '16 at 12:05

0 Answers0