2

I've rewritten the underscore.js delay function to look like the below. It works after tinkering with using apply() but I don't fully understand what the "this" in the apply is pointing to in the anonymous function within setTimeout.

_.delay = function(func, wait) {
   var args = Array.prototype.slice.call(arguments, 2);
     setTimeout(function() {
       return func.apply(this, args);
     }, wait);
 };
Artiom
  • 7,694
  • 3
  • 38
  • 45

1 Answers1

1

this refers to window inside the setTimeout() and setInterval() functions. If you want to avoid this side effect, you can "bind" the value of this:

_.delay = function(func, wait, thisArg) {
   var args = Array.prototype.slice.call(arguments, 2);
   thisArg = thisArg || this;//assume a default value
   setTimeout(function() {
     return boundFunction.apply(thisArg, args);
   }, wait);
};

Then you can pass what will be the value of this to _.delay() or let it be _ by default.

Another way is to bind your function before passing it to _.delay():

function a() {console.log(this);}
_.delay(a.bind({foo:'bar'}), 1000); //prints {foo: 'bar'}
AlexStack
  • 16,766
  • 21
  • 72
  • 104