Skip to main content

A little lesson on binding

· 2 min read

I've been writing JavaScript for the past 10 years for my work, and there are still things in the language that trips me up. A very good example is on binding.

Given the setup below, I would have been a little hesitant as to what the right answer is.

function Alpha() {
this.name = 'A';
}

Alpha.prototype.say = function () {
return this.name;
}

function Beta() {
this.name = 'B';
}

Beta.prototype.say = function () {
return this.name;
}

var name = 'G';

function say() {
return this.name;
}

function echo(action) {
console.log(action());
}

a = new Alpha();
b = new Beta();

a.say(); // returns A
b.say(); // returns B
say(); // returns G

Nothing fancy up to this point. But the next 2 lines will make me think a bit.

echo(a.say);
// Output: 'G'
echo(a.say.bind(a))
// Output: 'A'

This next part is the kicker.

function Delta() {
this.name = 'D';
this.say = this.say.bind(this);
}

Delta.prototype.say = function () {
return this.name;
}

d = new Delta();

d.say();
echo(d.say);

What do you think the output is?

ANSWER

Both lines output "D".

This example shows that there is a case for early binding even on prototype methods.