0

Uncaught TypeError: Illegal invocation

I'm having this error when trying delay all ajax requests in my application.

(function(send) {
  XMLHttpRequest.prototype.send = function(data) {
    setTimeout( function () {
      send.call(this, data); //Error here
    },3000);
  };
})(XMLHttpRequest.prototype.send);

Could you give me some hints? Thanks in advance.

fluis
  • 15
  • 4
  • I think, here, `this` will refer to **setTimeout** function – Abhi May 09 '17 at 15:52
  • How can i change that? – fluis May 09 '17 at 15:54
  • Possible duplicate of [Why are certain function calls termed "illegal invocations" in JavaScript?](http://stackoverflow.com/questions/10743596/why-are-certain-function-calls-termed-illegal-invocations-in-javascript) – Christoph May 09 '17 at 15:54
  • @fluis save it into a variable like: `var _this = this` before calling `setTimeout` – Abhi May 09 '17 at 15:58
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Andreas May 09 '17 at 16:02

1 Answers1

0

It seems you are calling .call passing in the current scope which would be window.

(function(send) {
  XMLHttpRequest.prototype.send = function(data) {
    var self = this;
    setTimeout( function () {
      send.call(self, data); //Updated `this` context
    },3000);
  };
})(XMLHttpRequest.prototype.send);
MattSizzle
  • 3,145
  • 1
  • 22
  • 42