Good morning, gentlemen. The code of the wrapper function adds the elements from the agruments the sum function into an argsArr array.

 "use strict"; var argsArr = []; function funcLog(f, argsArr) { return function() { var wrapper = f.apply(this, arguments); var argsArrLocal = [].slice.call(arguments); for (var i = 0; i < argsArrLocal.length; i++) { argsArr.push(argsArrLocal[i]); } return wrapper; }; } function sum(a,b) { alert(a+b+b); } sum = funcLog(sum, argsArr); sum(2,3); alert(argsArr); 

The first version of the code was this.

 "use strict"; var argsArr = []; function funcLog(f, argsArr) { return function() { var wrapper = f.apply(this, arguments); argsArr = [].slice.call(arguments); return wrapper; }; } function sum(a,b) { alert(a+b+b); } sum = funcLog(sum, argsArr); sum(2,3); alert(argsArr); 

But, he did not work. The array, argsArr , was not overwritten, and why I did not know. I suspect that I was mistaken somewhere, but I don’t understand the essence of the error. Direct on the right path.

  • why assignment does not work? everything works fine - Grundy
  • Maybe you just expect some other result? - Grundy
  • argsArr = []. slice.call (arguments); - Alexander Korinskiy
  • Without var, otherwise it will create a local variable. - Alexander Korinskiy
  • and? What do these comments mean? Everything works exactly as it should. What exactly does not suit you? - Grundy

1 answer 1

The whole problem is using the wrong function.

 function funcLog(f, argsArr) { 

As you can see the name of the second parameter argsArr , any actions with this name inside the function are performed with the parameter, and not with the global variable of the same name.

The easiest way to make the first code work is to simply remove this parameter from the function definition.

 function funcLog(f) { 

Why does this work in the second case?

Since the global array is passed to the function, this parameter refers to the global variable, therefore when calling methods that directly change the object, the changes were also displayed on the global variable.

At assignment, there was just a change of reference for the parameter.

  • If I did not know this before - I would not understand what is written here. - Pavel Mayorov
  • @PavelMayorov, straight really, completely incomprehensible? Like the main idea - to remove the parameter - is clearly visible? - Grundy
  • And what if you need to collect the arguments in two different arrays? - Pavel Mayorov
  • @PavelMayorov, and where does the author want to collect in two different arrays? :-) he has both options all put in one. - Grundy
  • @PavelMayorov, well, as far as I understand it, it is enough to move this array into a function - Grundy