What are the dangers of using Mutable thisarg or context with javascript

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}));
// outputs [1, 2, 3, 5, 6, 7]

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));
// outputs [1, 2, 3, 5, 6, 7]

// now using the **same** context, continue with arr1
console.log(arr1.filter(increasingValue, context));
// outputs [9, 12]
+4
1

,

var increasingFrom = function(init) {
    var highestValue = init;
    return function(i) {
        if (highestValue < i) {
            highestValue = i;
            return true;
        }
        return false;
    };
}

console.log(arr.filter(increasingFrom(0)));
+2

Source: https://habr.com/ru/post/1618036/


All Articles