0

Well the problem is with the Game's instance of rects: [], which should be array of objects Rect. When i access the rects property inside Game gives undefined.

http://jsbin.com/ibilec/34/edit

(function(window, document, console) {
  'use strict';

  function Rect() {
    this.x = 0;
    this.y = 0;
    this.width = 20;
    this.height = 20;
  }

  Rect.prototype.draw = function(ctx) {
    ctx.fillRect(this.x, this.y, this.width, this.height);
  };


  var Game = Object.create({    
    rects: [],  /// PROBLEM IS WITH this

    draw: function() {
      console.log('Draw called', this.rects);
      if (this.rects) {
        this.rects.forEach(function(rect, index) {
          console.log(rect);
          rect.draw(this.ctx);
        });
      }

      //window.setInterval(function() { this.ctx.clearRect(0, 0, 200, 200); }, 1000);


    },

    genRect: function() {
      var newRect = new Rect();
      newRect.x = parseInt(Math.random() * 200, 10);
      newRect.y = parseInt(Math.random() * 200, 10);

      this.rects.push(newRect);
    },

    loop: function() {
      //Game.draw();
      // Frame rate about 30 FPS

      window.setInterval(this.draw, 1000 / 30);
    },

    init: function() {
      this.canvas = document.getElementById('game'); 
      this.height = this.canvas.height;
      this.width = this.canvas.width;

      window.ctx = this.canvas.getContext('2d');


      this.genRect();
      this.loop(); //start loop
    }
  });

  var game = Object.create(Game);
  game.init();
})(window, document, console);

1 Answer 1

2

The draw method is not called as a method of the object, it's called as a function in the global scope, so this will be a reference to window, not to the Game object.

Copy this to a variable, and use it to call the method from a function:

var t = this;
window.setInterval(function() { t.draw(); }, 1000 / 30);
Sign up to request clarification or add additional context in comments.

8 Comments

This line rect.draw(this.ctx); is also incorrect because the ctx is saved to global scope here window.ctx = this.canvas.getContext('2d');
@PeterPajchl: But that code is run inside a callback function, so this will be the window object.
which callback? the one in your answer?
@PeterPajchl: No, the callback for the forEach.
please correct me if I am wrong but based on documentation - if thisArg is undefined or null the this value depends on whether it's run in strict mode or not -> only in non-strict mode this value will refer to global object developer.mozilla.org/en-US/docs/JavaScript/Reference/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.