title: javascript object, self reference problem
body: <p>I just started using oop in javascript and I ran across some problems trying to acces a method from inside another method.</p>
  
  <p>here's the code I had:</p>
  
  <pre><code>var Game = {
  initialize: function () {
      if (canvas.isSupported()) {
          sprites[0] = new Player();
  
          this.update();
      }
  },
  
  update: function() {
      for (var i = 0; i &lt; sprites.length; i++) {
          sprites[i].update();
      }
  
      this.draw();
  },
  
  draw: function() {
      this.clear();
  
      for (var i = 0; i &lt; sprites.length; i++) {
          sprites[i].draw();
      }
  
      setTimeout(this.update, 10);
  },
  
  clear: function() {
      canvas.context.clearRect(0, 0, canvas.element.width, canvas.element.height);
  }
  </code></pre>
  
  <p>}</p>
  
  <p>but calling the Game.update() gives an error that the draw method isn't defined.
  I couldn't find a real solution for this.
  eventually I found this <a href="https://stackoverflow.com/questions/4393351/how-to-call-a-method-inside-a-javascript-object">How to call a method inside a javascript object</a>
  where the answer seems to be that I need to safe the this reference like:
  <code>var _this = this;</code>
  but I couldn't get that to work in literal notation, so I changed the code to object constructor (I guess that's how it's called) and added the variable.</p>
  
  <p>I then changed  </p>
  
  <pre><code>this.draw();
  </code></pre>
  
  <p>to</p>
  
  <pre><code>_this.draw();
  </code></pre>
  
  <p>and it worked.</p>
  
  <p>though the </p>
  
  <pre><code>this.clear();
  </code></pre>
  
  <p>and the this.update() are still the same, they never seemed to give errors in the first place. </p>
  
  <p>Can anyone explain why this is? and maybe point me to a better solution?
  thanks in advance.</p>
  
  <p><strong>update</strong></p>
  
  <p>Here's what it should be:</p>
  
  <pre><code>var Game = function () {
  var _this = this;
  
  this.initialize = function () {
      if (canvas.isSupported()) {
          sprites[0] = new Player();
  
          this.update();
      }
  }
  
  this.update = function () {
      for (var i = 0; i &lt; sprites.length; i++) {
          sprites[i].update();
      }
  
      this.draw();
  }
  
  this.draw = function () {
      this.clear();
  
      for (var i = 0; i &lt; sprites.length; i++) {
          sprites[i].draw();
      }
  
  
      setTimeout(function () { _this.update(); }, 10);
  }
  
  this.clear = function () {
      canvas.context.clearRect(0, 0, canvas.element.width, canvas.element.height);
  }
  </code></pre>
  
  <p>}</p>