How to use a function of an object as an argument of another function

Asked

Viewed 45 times

2

This is my function that receives an object and uses the attributes of type "Function".

FrameWork.prototype.loop = function (objectLoop) {

    objectLoop.draw();
    objectLoop.update();
    window.requestAnimationFrame(this.loop.bind(this));
};

This is the object I pass to the loop Function (game is my instance of Framework and Framework is in a separate . js file)

game.loop({
        draw : function(){

            game.get.Context.clearRect(0, 0, 100, 100);

            game.get.Context.fillStyle = colider.color;
            game.get.Context.fillRect(colider.x, colider.y, colider.width, colider.height);

            game.get.Context.fillStyle = player.color;
            game.get.Context.fillRect(player.x, player.y, player.width, player.height);
        },
        update: function () {
            updateBlock();
            colide();
            wallCollision();
        }
    });

Error:

Uncaught TypeError: objectLoop.draw is not a function.

1 answer

3


When you pass the callback to window.requestAnimationFrame the function loop will be run again. It will run with the right context because you use .bind(this) but without arguments. The objectLoop will not be defined if you do not pass it in the .bind also;

To pass also this object uses so:

window.requestAnimationFrame(this.loop.bind(this, objectLoop));
  • 1

    It worked! Thank you (it’s funny to be just a detail of this).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.