Jas Jas - 18 days ago 10
Javascript Question

How to overcome "potentially invalid usage of this"?

I get potentially invalid usage of

this
when calling
isDataMatchingnamespace
how to overcome and how to call
isDataMatchingnamespace
in a proper way?

function Client() {

var namespace = "default";

this.addnamespaceTodata = function(data) {
data.namespace = namespace;
return data;
};

this.isdataMatchingnamespace = function(data) {
return data.namespace === namespace;
};

this.filterdatasBynamespace = function(datas) {
var result = [];
_.forEach(datas, function(data) {
if (this.isdataMatchingnamespace(data)) { // I get potentially invalid usage of this so how to overcome and how to call isDataMatchingnamespace in a proper way?
result.push(data);
}
});
}
}

module.exports = Client;

Answer

That is an invalid usage of this, since this is undefined inside that function.

underscore.js allows you to pass an optional additional argument to forEach to specify what this should be inside the function. If you want it to be the same as this from outside the function, then pass this as the third argument into _.forEach:

    _.forEach(datas, function(data) {
        if (this.isdataMatchingnamespace(data)) {
            result.push(data);
        }
    }, this); // Added ", this"
Comments