Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overcome "potentially invalid usage of this"?

Tags:

javascript

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;
like image 666
Jas Avatar asked Nov 15 '16 08:11

Jas


2 Answers

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"
like image 197
Paul Avatar answered Oct 26 '22 09:10

Paul


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;

like image 43
spankajd Avatar answered Oct 26 '22 11:10

spankajd