No binding necessary

How to avoid having to bind functions to contexts.

JavaScript allows returning references to object's methods, and using them as regular functions. This often causes exceptions (in strict mode), because the method tries to use this reference, which is undefined when calling the function without object context.

1
2
3
4
5
6
7
8
9
10
var foo = {
name: 'foo',
printName: function () {
'use strict';
console.log(this.name);
}
};
foo.printName(); // works fine
var fooName = foo.printName; // 2
fooName();
// output
foo
/index.js:5
  console.log(this.name);
TypeError: Cannot read property 'name' of undefined
    at foo.printName (/index.js:5:21)

Typical solution is to bind the function returned in line // 2 to the object foo.

1
2
var fooName = foo.printName.bind(foo);
fooName(); // prints 'foo'

But sometimes using bind is not necessary. If a function does not use this, then there is nothing to gain by binding it to the object. A good example is console object. Its methods (log, info, warn, error, assert, etc) do not use this context, they act more like static methods.

1
2
3
var foo = console.log;
foo('no', 'binding', 'necessary');
// output "no binding necessary"

Another example are any objects constructed using a module pattern, that keep their properties inside an external closure

1
2
3
4
5
6
7
8
9
10
11
12
13
var Foo = function () {
var name = 'foo';
return {
printName: function () {
'use strict';
console.log(name);
}
};
};
var foo = Foo();
var fooName = foo.printName;
fooName();
// output "foo"

Everything works fine here, proving once again that using bind is not necessary in every situation.