简体   繁体   中英

calling a prototype method from another - getting 'undefined' error

In brevity, this is how my Nodejs controller looks

I am trying to call 'getFqUrl' from another prototype method 'getData' using this. but am getting 'undefined' error.

I referred to this SO Q&A and to me, my code looks exactly the same.

    function SolrFacetClient() {
        this.fieldNames = fieldNames;
        this.facets = new Map();
    }
    SolrFacetClient.prototype.getFqUrl = function(fq){
        var url = '&fq=';
        console.log(fq);
    }
    SolrFacetClient.prototype.getData = function (fieldName,fq) {
        var a = this.getFqUrl;
        console.log(a(fq)); //this doesn't work. getting 'undefined' 
    }
    SolrFacetClient.prototype.init = function (fq) {
      //Updated this section after question was posted.
      //this works
        var aRef =   this.getFqUrl;
        aRef(fq);
       //Update ends    
        var getSolrData = this.getData;
        return getSolrData(item,fq);
    };
    exports.facets = function (req, res) {
        var facetClient = new SolrFacetClient();
        var fq = new Map();
        facetClient.getFqUrl(fq); //this works 

        when(facetClient.init(fq), function(result){
            res.jsonp(result);
        })
    }

When you separate a function from an object context and call it, the result is that the value of this in the called function won't be what it was written to expect.

Thus, in this code:

    var getSolrData = this.getData;
    return getSolrData(item,fq);

things would work correctly if it looked like

    return this.getData(item, fq);

It does not work in your version, however, because the getData() function expects this to refer to an object instance. Unlike a lot of other programming languages, JavaScript doesn't maintain any long-term relationship between a function and any particular object (or "class", which is a tricky term to use in JavaScript) unless you explicitly ask for that with .bind() or something similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM