In javascript this
is function scoped, so creating a new function creates a new this
.
Your forEach
call has a callback, which is a function, and within that function this
is no longer the string, but most likely the window
The solution is to simply store a reference to whatever this
is in the outer function
String.prototype.includesAny = function(search) {
var found = false,
input = this;
search.forEach(function(str) {
if (input.toLowerCase().includes(str.toLowerCase())) {
found = true;
}
});
return found;
};
Array.forEach
also has an optional thisArg
that can be used
String.prototype.includesAny = function(search) {
var found = false;
search.forEach(function(str) {
if (this.toLowerCase().includes(str.toLowerCase())) {
found = true;
}
}, this);
return found;
};
Or even better, use Array.some
String.prototype.includesAny = function(search) {
return search.some(function(str) {
return this.toLowerCase().includes(str.toLowerCase());
}, this);
};
As a sidenote, extending native prototypes is generally a bad idea.