javascript - cannot access 'this' in nested function -
javascript - cannot access 'this' in nested function -
this question has reply here:
javascript “this” pointer within nested function 5 answers how access right `this` / context within callback? 4 answersso need help i've been stuck on couple of hours now..
the problem i'm creating object called rank. rank needs db calls in mongodb info fill matrix, needs perform more nested function calls on matrix haven't written yet. problem when i'm calling dorank() gets companies , transactions , seems set them in rank when phone call creatematrix can't access 'this'
i have tried using .bind(this) on each of functions in dorank() prevents error method doesn't exist when console.log @ end of dorank() results matrix undefined.
function rank(dampingfactor){   this.damping_factor = dampingfactor;   this.companies = null;   this.transactions = null;   this.matrix = null;    this.dorank(function(){     //companies returns valid     console.log(this.companies);     //transactions  homecoming valid     console.log(this.transactions);     //matrix returns undefined... help here please     console.log(this.matrix);   }); };  rank.prototype.dorank = function(callback) {   this.gettransactions(function() {     this.getcompanies(function () {         this.creatematrix(function(){             callback();         }.bind(this));     }.bind(this));   }.bind(this)); };  rank.prototype.gettransactions = function(callback){   transaction.find({}, function(err, transactions) {     //blah blah blah     this.transaction = transactions;     callback();   }); };  rank.prototype.getcompanies = function(callback){   company.find({}, function(err, comps) {     //blah blah blah     this.transaction = comps;     callback();   }); };  rank.prototype.creatematrix = function(callback){   console.log(this.companies)   //this returns "null"   var matrix = new array(_.size(this.companies));   for(var = 0; < _.size(this.companies); i++){       matrix[i] = new array(_.size(this.companies));       for(var j=0; j < _.size(this.companies); j++){         matrix[i][j] = 0;       }   }   this.matrix = matrix;   callback(); };       
you losing context in ajax callback functions  within gettransactions , getcompanies too.  seek 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)); };        javascript node.js 
 
  
Comments
Post a Comment