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.