This is similar to the forEach method. The forEach method, as is known, can take the following parameters (callback[, thisArg]) . Here is a function that is analogous to this method.

How to add thisArg parameter (Optional parameter. Value used as this when calling the callback function)?

 var array = [1, 2, 3, 4, 5, 6]; console.log(customForEach(array, func)); function customForEach(src, callback) { for (var i = 0; i < src.length; i++) { callback(src[i], i, src); } } function func(item, i, arr) { console.log(i + ' Элемент: ' + item + '(массив ' + arr + ')'); } 

  • console.log(customForEach(array, func)); - What do you expect to see in the console? - Igor
  • something like callback.call (thisArg, src [i], i, src). The function is called in the right context - the apply and call methods, I think the cause of the question is in ignorance of what it is) - Duck Learns to Take Cover
  • @ Moderately Tilting I Read MDN and I Can’t Understand) Trying to figure it out with a specific example. - ra.chobanyan Nov.
  • at the same time you can see the answers to the question: the loss of the context of the call - Grundy Nov.
  • @Igor for the first element of the array "0 Element: 1 (array 1,2,3,4,5,6)" and so on. - ra.chobanyan Nov.

1 answer 1

When using the call and apply functions, you can set this value directly by passing it to the first parameter.

The difference between these methods in the way parameters are passed:

  1. If the number of parameters is known in advance, then it is easier to use the call function, in which the parameters of the called function are comma-separated

     callback.call(thisArg, src[i], i, src); 
  2. If the parameter list is collected dynamically, then it is better to use apply , which takes an array-like object or an array with the passed parameters as the second parameter.

     callback.apply(thisArg, [src[i], i, src]); 

Example:

 var o = { a: 1, b: 2, c: 3 } console.log('Пример с передачей this'); customForEach(Object.keys(o), func, o); var array = [1, 2, 3, 4, 5, 6]; console.log('Пример без передачи this'); customForEach(array, func2); function customForEach(src, callback, thisArg) { for (var i = 0; i < src.length; i++) { callback.call(thisArg, src[i], i, src); } } function func(item, i, arr) { console.log(i + ' Элемент: ' + item + '(массив ' + arr + ')' + ', значение: ' + this[item] + '(this:' + JSON.stringify(this) + ')'); } function func2(item, i, arr) { console.log(i + ' Элемент: ' + item + '(массив ' + arr + ')'); } 
 .as-console-wrapper { top: 0; max-height: 100% !important; } 


You can learn more about the context change in the question:

Loss of call context