Context Binding

introduction to context binding, animation of a ball using the setInterval method

We'll cover the following...

In ES5, function scope often requires us to bind the context to a function. Context binding is usually performed in one of the following two ways:

  1. by defining a self = this variable,
  2. by using the bind function.

In our first example, we will attempt to animate a ball using the setInterval method.

Press + to interact
var Ball = function( x, y, vx, vy ) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.dt = 25; // 1000/25 = 40 frames per second
setInterval( function() {
this.x += vx;
this.y += vy;
console.log( this.x, this.y );
}, this.dt );
}
var ball = new Ball( 0, 0, 10000, 10000 );

The ...