简体   繁体   中英

What is the value of "this" within an anonymous function in setTimeout below?

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);
 };

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'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM