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;
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"
there is other way also by storing this value into variable.
let's say var _thisRef = this; define this below var namespace = "default"; and use _thisRef.isdataMatchingnamespace(data) without changing your code
your updated code as follow :
function Client() {
var namespace = "default";
var _thisRef = this;
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 (_thisRef.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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With