This question has already been answered:

Assignment: Add a defer (ms) method to all functions in the prototype, which returns a wrapper that defers a function call for ms milliseconds. It is clear, only that line 3 binds the context and arguments to the returned wrapper, which are taken from the closure

It is not clear why this code is saved twice? In the line (1) the delayed function is saved, but why then the line with the context (2) arguments was transferred to the returned function? Why didn't they declare this variable before return? At the same time, in the second line, the context seems to be equal to underfined

Function.prototype.defer = function(ms) { var f = this; // (1) return function() { var args = arguments, context = this; // (2) setTimeout(function() { f.apply(context, args); // (3) }, ms); } } // проверка function f(a, b) { alert( a + b ); } f.defer(1000)(1, 2); 

Reported as a duplicate by Kromster members, 0xdb , LFC , aleksandr barakin , Grundy javascript Feb 10 at 9:55 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • "in the second line, the context seems to be equal to under" "- how did you find out? - Igor

1 answer 1

Because the parameters for the summing function function f(a, b) appear only in the second call. That is, in the call to the anonymous function returned from defer .

The context in the second call, stored in context , is window .

  • and in strict mode, isn't the context equal to under?? - ZdraviSmisl pm
  • one
    @ZdraviSmisl in strict - yes - Igor
  • one
    @ZdraviSmisl undefined - Igor