0

I want to make a select option for animations, so whatever type is selected, it's shown on the canvas. So i make each animation as a "class" :

(function (exports) {

  function animationA() {}
  animationA.prototype.init = function(){}
  animationA.prototype.draw = function(){}

  exports.animationA = animationA;
})(this);

Then in the main js:

var a = new animationA();

  function setup() {
    a.init();
  }

  function update(callback) {
    requestAnimationFrame(function () {
      update(callback);
    });
    console.log(this);
    callback();
  }

  setup();
  update(a.draw);

I found error occurs in the update(a.draw). It cannot access the properties of a in this line of code. I wonder if this is a javascript scope problem?

Thanks.

kikkpunk
  • 1,287
  • 5
  • 22
  • 34
  • It's not about the `requestAnimationFrame` function that you use. It's about how you pass `a.draw` to `update` – Bergi Jul 20 '14 at 16:19
  • The [`this` keyword](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) is not the *scope* of a function, it's the `context` of a function call. – Bergi Jul 20 '14 at 16:21

1 Answers1

0

You need to create a reference to the context you want to refer to inside the callback before you call requestAnimationFrame, just like you would with a normal event callback.

Var that = this;

requestAnimationFrame(function(){

that.doSimething();

});
Chris Love
  • 3,740
  • 1
  • 19
  • 16
  • 1
    What is `RequestAnimationFrame`? What is `This`? – Bergi Jul 20 '14 at 16:21
  • requestAnimationFrame is a function that executes when the browser updates the screen based on the graphic card's refresh rate. Since most displays operate at 60Hz the function fires every 16.6666ms. The callback function is executed when the function fires. Since there are variations when the screen actually refreshes it is not always 16.6666ms, so requestAnimationFrame is much more efficient than doing a setInterval or setTimeout function. – Chris Love Jul 21 '14 at 10:30
  • Oh, that one is called `requestAnimationFrame`. Thanks for the update! – Bergi Jul 21 '14 at 10:54