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 | var foo = { |
// 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 | var fooName = foo.printName.bind(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 | var foo = console.log; |
Another example are any objects constructed using a module pattern, that keep their properties inside an external closure
1 | var Foo = function () { |
Everything works fine here, proving once again that using bind
is
not necessary in every situation.