Accessing global array using "this" in prototype function

Hello js people,
Trying to solve a problem related to JS functional programming. The solution is given below:

// The global variable
var s = [23, 65, 98, 5];

Array.prototype.myFilter = function(callback) {
  // Only change code below this line
  console.log(this); //this prints [ 23, 65, 98, 5 ]
  var newArray = [];
  this.forEach(val => {
    if(callback(val) == true){
      newArray.push(val)
    }
  });
  // Only change code above this line
  return newArray;
};

var new_s = s.myFilter(function(item) {
  return item % 2 === 1;
});
console.log(new_s); // this prints [ 23, 65, 5 ]

My problem is with the this syntax used in myFilter function. The console.log(this); prints [ 23, 65, 98, 5 ] which is global s array. I think i did not understand the use of this in the myFilter function.
Can someone explain it to me how this this actually works here?
I meant, how come this this indicates global s array?
Note: I am learning JS.

this is referring to the array that myFilter is being applied to.

s.myFilter(function(item) {
  return item % 2 === 1;
});

In this example, s is the array that is calling myFilter so this inside of the myFilter method is the array s.

That s is declared as a global variable does not factor into it.

Here is a pretty good article on this.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.