This question has already been answered:
- Loss of context call 5 responses
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);