cannot access 'this' in nested function

This question already has an answer here:

  • How to access the correct `this` inside a callback? 6 answers
  • Javascript “this” pointer within nested function 7 answers

  • You are losing context in AJAX callback functions inside getTransactions and getCompanies too. Try this:

    Rank.prototype.getTransactions = function(callback) {
        Transaction.find({}, function(err, transactions) {
            //blah blah blah
            this.transaction = transactions;
            callback();
        }.bind(this));
    };
    
    Rank.prototype.getCompanies = function(callback) {
        Company.find({}, function(err, comps) {
            //blah blah blah
            this.transaction = comps;
            callback();
        }.bind(this));
    };
    

    this no longer refers to an object when used inside nested function calls, as the function does not have a parent object. If you assign this to a variable eg var self = this , you can access it like normal inside nested function calls.

    链接地址: http://www.djcxy.com/p/94896.html

    上一篇: 我的javascript范围有什么问题

    下一篇: 不能在嵌套函数中访问'this'