0

Possible Duplicate:
Nested function parameters and 'this' context in Javascript

I'm currently having problems to design my JS classes as desired due to a problem using 'this' in a nested class function call. Don't know how to describe it better so here's a sample what I mean.

test.html

<!DOCTYPE html>
<html class="main" lang="en">
<head>
    <meta charset="utf-8">
    <script type="text/javascript" src="test.js"></script>
    <script type="text/javascript">
        function doIt() {
            var myTestClass = new TestClass();
        }
    </script>
</head>
<body>
    <button onclick="doIt();">Do it!</button>
</body>
</html>

test.js

function TestClass() {
   // this is working
   this.alertValue('This works');

   // this is not working
   setTimeout(function(){this.alertValue('This does not work!')}, 1000);
}

TestClass.prototype.alertValue = function(value) {
   alert('Value is: ' + value);
}

Of course this is just a simplified example to demonstrate the problem I mean. So how could I use the 'this' identifier within the function inside the setTimeout call or how would be a better / the correct way to achieve that?

Thanks a lot for your help in advance! Cheers

3
  • 1
    this question seems to be asked a dozen times every day Commented Aug 22, 2012 at 11:26
  • It's important to know that this is set (or "reset" if you will) on every function call. Commented Aug 22, 2012 at 11:26
  • Sorry to ask such a common question but I honestly searched for an answer before posting but the problem in finding the right answer was that all keywords are much generic :-/ Commented Aug 22, 2012 at 11:36

1 Answer 1

5

Save the value of this in a variable (self) and then you can access it within setTimeout.

function TestClass() {
   this.alertValue('This works');
   var self = this;
   setTimeout(function() { 
     self.alertValue('This does not work!')
   }, 1000);
}
Sign up to request clarification or add additional context in comments.

6 Comments

I'd suggest something more descriptive than self, though. Perhaps testClass would be useful.
@ScottSauyet: Hi, it's just a convention used by many libraries, such as jQuery, to name self the cached reference to the instance.
Understood. I disagree with the convention. What do you do if you nest another level, self2?! Using a more descriptive name is IMHO much more useful.
Thanks a lot for that immediately answer!
@ScottSauyet: I understand your point, but I'd prefer not to have more than one nested level; it can be quite confusing.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.