I'm new to javascript and wondering about wisdom using thisarg variable for functions like map, foreach and filter.
Consider the following
function increasingValueFn(i)
{
if (this.highestValue < i)
{
this.highestValue = i;
return true;
}
return false;
}
This function will allow us to pass the object as thisarg, as in the following examples.
var arr = [1, 2, 3, 2, 1, 5, 6, 7];
console.log(arr.filter(increasingValueFn, {highestValue: 0}));
and using the same magnificationValueFn
var arr2 = ["cat", "dog", "aardvark", "zebra"];
console.log(arr2.filter(increasingValue, {highestValue: ""}));
// outputs ["cat", "dog", "zebra"]
These are simple examples. Imagine a case where we are trying to create a much more arbitrary answer with very complex rules for inclusion, in which case we could make arbitrary changes in our state, and then run a simple predicate based on this state, which returns yes or no.
, , , - .
, ? ?
, , thisarg? , , :
var arr = [1, 2, 3, 2, 1, 5, 6, 7];
var arr1 = [3, 7, 9, 4, 2, 12];
var context = {highestValue: 0};
console.log(arr.filter(increasingValue, context));
console.log(arr1.filter(increasingValue, context));