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,021
  • 3
  • 34
  • 43

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
  • 13,994
  • 14
  • 68
  • 98