I have an existing project that (sadly) uses underscore.js, rather than an ES5 shim, to support IE8 and other non-ES5 browsers. I’m used to ES5, but don’t generally use underscore. I have read the underscore documentation on _.bind and attempted to get it to work.
Here is a working example using native ES5:
// Greets people
HelloThing = function (greeting) {
this.greeting = greeting;
this.waitAndSayHello = function() {
setTimeout(function() {
console.log(this.greeting)
}.bind(this), 500);
}
}
var pretend_thing = new HelloThing('hello world');
pretend_thing.waitAndSayHello();
Here is a failing attempt using underscore from my understanding of the documentation:
// Greets people
HelloThing = function (greeting) {
this.greeting = greeting;
this.waitAndSayHello = function() {
var greet = function() {
alert(this.greeting)
}
_.bind(greet, this)
setTimeout(greet, 500);
}
}
var pretend_thing = new HelloThing('hello world');
pretend_thing.waitAndSayHello();
How can I make underscore work?
The
_.bind()method returns a bound function. You don’t do anything with that returned function. Assign it to something and use that reference instead of the originalgreetreference:If you expand your ES5 example, you will see that this is effectively what is happening with the native
bindmethod – you can just call directly on a function object since it’s a property ofFunction.prototype: