Skip to content

Instantly share code, notes, and snippets.

@maxleiko
Created August 4, 2016 08:59
Show Gist options
  • Save maxleiko/0d083767b92a6b338e0720bda4b31da7 to your computer and use it in GitHub Desktop.
Save maxleiko/0d083767b92a6b338e0720bda4b31da7 to your computer and use it in GitHub Desktop.
'use strict';
function MyType() {
this.id = null;
}
MyType.prototype.handler = function () {
console.log('handle ' + this.id);
};
var t = new MyType();
t.id = 42;
function caller(fn) { // same goes for setTimeout(), etc...
fn();
}
caller(t.handler); // this throw an error because t.handler will be called without the context
caller(t.handler.bind(t)); // this works because bind(ctx) returns a function with the given "ctx"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment