Javascript: using the apply method

- 1 answer

Ad

Here's my code:

var add = function(x,y) {
  console.log(x + y);
}


var delay = function(func, wait) {
  var inner = function() {
    return setTimeout(function() {
      return func.apply(inner, arguments);
    }, wait);
  }
  return inner;
};

var delayAdd = delay(add, 500);

delayAdd(100,200); //should log 300 to console after 500ms
                   //instead, it logs NaN

I suspect the problem is in line 9: return func.apply(inner, arguments); My intention is for add to be called on the arguments in inner, which are defined in the last line delayAdd(100,200). However, this does not seem to be happening. Why is this, and how can I fix this issue?

Ad

Answer

Ad

The arguments keyword is specific to the scope it's being referenced from. As it is, you're passing the arguments from your setTimeout function. What you need to do is save a reference from the scope you want, and pass that:

   var inner = function() {
      var args = arguments;
      return setTimeout(function() {
         return func.apply(inner, args);
         ...
Ad
source: stackoverflow.com
Ad