Search⌘ K

Context Binding

Explore how ES6 arrow functions offer automatic context binding in JavaScript, eliminating the need for manual binding techniques from ES5. Understand the limitations of traditional methods and see practical examples demonstrating improved syntax and scope handling with arrow functions.

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.

Node.js
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 ...